【发布时间】:2017-02-18 00:27:22
【问题描述】:
当对象具有@XmlAnyElement 属性时,我目前面临一个奇怪的 JAXB 命名空间行为。
这里是设置:
包信息.java
@XmlSchema(
namespace = "http://www.example.org",
elementFormDefault = XmlNsForm.QUALIFIED,
xmlns = { @javax.xml.bind.annotation.XmlNs(prefix = "example", namespaceURI = "http://www.example.org") }
)
类型定义:
@XmlRootElement
@XmlType(namespace="http://www.example.org")
public class Message {
private String id;
@XmlAnyElement(lax = true)
private List<Object> any;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<>();
}
return this.any;
}
}
以及测试代码本身:
@Test
public void simpleTest() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Message.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
String xml =
"<example:message xmlns:example=\"http://www.example.org\" xmlns:test=\"http://www.test.org\" xmlns:unused=\"http://www.unused.org\">\n" +
" <example:id>id-1</example:id>\n" +
" <test:value>my-value</test:value>\n" +
" <test:value>my-value2</test:value>\n" +
"</example:message>";
System.out.println("Source:\n"+xml);
// parsed
Object unmarshalled = unmarshaller.unmarshal(new StringReader(xml));
// directly convert it back
StringWriter writer = new StringWriter();
marshaller.marshal(unmarshalled, writer);
System.out.println("\n\nMarshalled again:\n"+writer.toString());
}
这种设置的问题是所有“未知”命名空间都被重复添加到任何元素中。
<example:message xmlns:example="http://www.example.org" xmlns:test="http://www.test.org" xmlns:unused="http://www.unused.org">
<example:id>id-1</example:id>
<test:value>my-value</test:value>
<test:value>my-value2</test:value>
</example:message>
变成这样:
<example:message xmlns:example="http://www.example.org">
<test:value xmlns:test="http://www.test.org" xmlns:unused="http://www.unused.org">my-value</test:value>
<test:value xmlns:test="http://www.test.org" xmlns:unused="http://www.unused.org">my-value2</test:value>
<example:id>id-1</example:id>
</example:message>
因此,我该如何避免这种情况!为什么不像在输入 xml 中那样在根元素中定义一次命名空间?由于 anyElement 的命名空间是未知的,因此无法通过包定义注册它...
此外,未使用的命名空间是否也可能被剥离(按需)?
【问题讨论】: