JAXB:如何避免 xmlns:xsi 的重复命名空间定义 [英] JAXB: How to avoid repeated namespace definition for xmlns:xsi
问题描述
我有一个 JAXB 设置,我使用 @XmlJavaTypeAdapter 将 Person
类型的对象替换为 PersonRef
类型的对象,该对象只包含个人的 UUID.这工作得很好.但是,每次使用生成的 XML 时都会重新声明相同的命名空间 (xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
).虽然这通常没问题,但就是感觉不对.
I have a JAXB setup where I use a @XmlJavaTypeAdapter to replace objects of type Person
with objects of type PersonRef
that only contains the person's UUID. This works perfectly fine. However, the generated XML redeclares the same namespace (xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
) every time it's used. While this is generally okay, it just doesn't feel right.
如何配置 JAXB 以在文档的最开始声明 xmlns:xsi?我可以手动向根元素添加命名空间声明吗?
How can I configure JAXB to declare xmlns:xsi at the very beginning of the document? Can I manually add namespace declarations to the root element?
以下是我想要实现的目标的示例:
Here's an example of what I want to achive:
当前:
<person uuid="6ec0cf24-e880-431b-ada0-a5835e2a565a">
<relation type="CHILD">
<to xsi:type="personRef" uuid="56a930c0-5499-467f-8263-c2a9f9ecc5a0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</relation>
<relation type="CHILD">
<to xsi:type="personRef" uuid="6ec0cf24-e880-431b-ada0-a5835e2a565a" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</relation>
<!-- SNIP: some more relations -->
</person>
通缉:
<person uuid="6ec0cf24-e880-431b-ada0-a5835e2a565a" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<relation type="CHILD">
<to xsi:type="personRef" uuid="56a930c0-5499-467f-8263-c2a9f9ecc5a0"/>
</relation>
<relation type="CHILD">
<to xsi:type="personRef" uuid="6ec0cf24-e880-431b-ada0-a5835e2a565a"/>
</relation>
<!-- SNIP: some more relations -->
</person>
推荐答案
你可以用代码来做:
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
@Override
public String[] getPreDeclaredNamespaceUris() {
return new String[] {
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI
};
}
@Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
if (namespaceUri.equals(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI))
return "xsi";
if (namespaceUri.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI))
return "xs";
if (namespaceUri.equals(WellKnownNamespace.XML_MIME_URI))
return "xmime";
return suggestion;
}
});
这篇关于JAXB:如何避免 xmlns:xsi 的重复命名空间定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!