我使用Jackson-dataformat-xml库将POJO序列化为Xml。
POJO:
public class Row2 {
public String getRn() {
return rn;
}
public void setRn(String rn) {
this.rn = rn;
}
public int getMobileNo() {
return mobileNo;
}
public void setMobileNo(int mobileNo) {
this.mobileNo = mobileNo;
}
@JsonAnyGetter
public Map<String, String> getOtherElements() {
return otherElements;
}
@JsonAnySetter
public void setOtherElements(Map<String, String> otherElements) {
this.otherElements = otherElements;
}
@JsonAnySetter
public void add(String key, String value) {
this.otherElements.put(key, value);
}
@JacksonXmlProperty(isAttribute=true)
private String rn;
private int mobileNo;
private Map<String, String> otherElements = new HashMap<>() ;
}
我正在使用以下代码对其进行序列化:
Row2 root2 = new Row2();
root2.setMobileNo(454);
root2.setRn("ResourceName");
Map<String, String> otherElements = new HashMap<String, String>() ;
otherElements.put("hey", "there");
otherElements.put("bye", "there");
root2.setOtherElements(otherElements );
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XMLInputFactory input = new WstxInputFactory();
input.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
WstxOutputFactory wstxOutputFactory = new WstxOutputFactory();
XmlMapper mapper = new XmlMapper(new XmlFactory(input, wstxOutputFactory), module);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
try {
PropertyName propertyName = new PropertyName("hd:binSh", "http://www.example.com/BAR");
String xml = mapper.writer().withRootName(propertyName).writeValueAsString(root2);
System.out.println("\nXML: \n" + xml );
} catch (IOException e) {
e.printStackTrace();
}
我得到的输出是:
<?xml version='1.0' encoding='UTF-8'?>
<hd:binSh xmlns="http://www.example.com/BAR" rn="ResourceName">
<mobileNo xmlns="">454</mobileNo>
<hey xmlns="">there</hey>
<bye xmlns="">there</bye>
</hd:binSh>
我想要的输出是:
<?xml version='1.0' encoding='UTF-8'?>
<hd:binSh xmlns:hd="http://www.example.com/BAR" rn="ResourceName">
<mobileNo>454</mobileNo>
<hey >there</hey>
<bye >there</bye>
</hd:binSh>
所以我想要在根元素上定义的名称空间前缀,例如<hd:binSh xmlns:hd="http://www.example.com/BAR" rn="ResourceName">
感谢您的帮助。