我有一个pojo,正在使用com.fasterxml.jackson.dataformat.xml.XmlMapper进行序列化。
我有一个用服务器字符串值定义的Java类。
@JacksonXmlRootElement(namespace = "http://www.firstnamespace.com", localName = "Student")
public class Student {
@JacksonXmlProperty(namespace = "http://www.firstnamespace.com",localName = "ID")
public final String id;
@JacksonXmlProperty(namespace = "http://www.firstnamespace.com",localName = "Name")
public final String name;
@JacksonXmlProperty(namespace = "http://www.firstnamespace.com",localName = "Address")
public Address address;
}
地址的定义是这样,地址的元素位于不同的命名空间中
public class Address {
@JacksonXmlProperty(namespace = "http://www.secondnamespace.com",localName = "StreetNumber")
public final String streetNumber;
@JacksonXmlProperty(namespace = "http://www.secondnamespace.com",localName = "StreetName")
public final String steetName;
}
当我用Jackson序列化Student时,我得到了一堆地址对象的重复命名空间。
<Student xmlns="http://www.firstnamespace.com">
<ID>1234</ID>
<Name>Ken</Name>
<Address>
<wstxns1:StreetNumber xmlns:wstnxs1="http://www.secondnamespace.com">Ken</wstxns1:StreetNumber>
<wstxns2:StreetName xmlns:wstnxs2="http://www.secondnamespace.com">Main Street</wstxns2:StreetName>
</Address>
我正在像这样序列化Student类:
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
xmlMapper.writeValue(new File("studentTest.xml", student);
File file = new File("studentTest.xml");
是否可以为给定名称空间创建单个名称空间前缀?
<Student xmlns="http://www.firstnamespace.com">
<ID>1234</ID>
<Name>Ken</Name>
<Address>
<wstxns1:StreetNumber xmlns:wstnxs1="http://www.secondnamespace.com">Ken</wstxns1:StreetNumber>
<wstxns1:StreetName>Main Street</wstxns1:StreetName>
</Address>
还是在顶部定义名称空间?
<Student xmlns="http://www.firstnamespace.com" xmlns:wstnxs1="http://www.secondnamespace.com">
<ID>1234</ID>
<Name>Ken</Name>
<Address>
<wstxns1:StreetNumber>Ken</wstxns1:StreetNumber>
<wstxns1:StreetName>Main Street</wstxns1:StreetName>
</Address>
我已阅读到我需要使用Woodstox来解决此问题,并且我尝试了以下方法,但是我看不到Woodstox配置如何帮助解决此问题。但是我可以更改前缀:
XMLInputFactory2 inputFactory2 = new WstxInputFactory();
XMLOutputFactory2 outputFactory2 = new WstxOutputFactory();
outputFactory2.setProperty(XMLOutputFactory2.P_AUTOMATIC_NS_PREFIX,"foo");
outputFactory2.configureForRobustness();
XmlFactory xmlFactory = new XmlFactory(inputFactory2,outputFactory2);
XmlMapper xmlMapper = new XmlMapper(xmlFactory);