在JAXB编组时删除名称空间前缀 [英] Remove namespace prefix while JAXB marshalling
问题描述
我有从架构创建的JAXB对象。在编组时,xml元素将使用ns2进行注释。我已经尝试过网络上存在的所有选项,但是这些选项都不起作用。我无法修改我的架构或更改package-info.java。请帮助
I have JAXB objects created from a schema. While marshalling, the xml elements are getting annotated with ns2. I have tried all the options that exist over the net for this problem, but none of them works. I cannot modify my schema or change package-info.java. Please help
推荐答案
经过大量的研究和修补,我终于设法解决了这个问题。请接受我的道歉,因为没有发布原始参考文献的链接 - 有很多我没有做笔记 - 但是这个一个肯定是有用的。
After much research and tinkering I have finally managed to achieve a solution to this problem. Please accept my apologies for not posting links to the original references - there are many and I wasn't taking notes - but this one was certainly useful.
我的解决方案使用过滤 XMLStreamWriter
,它应用空名称空间上下文。
My solution uses a filtering XMLStreamWriter
which applies an empty namespace context.
public class NoNamesWriter extends DelegatingXMLStreamWriter {
private static final NamespaceContext emptyNamespaceContext = new NamespaceContext() {
@Override
public String getNamespaceURI(String prefix) {
return "";
}
@Override
public String getPrefix(String namespaceURI) {
return "";
}
@Override
public Iterator getPrefixes(String namespaceURI) {
return null;
}
};
public static XMLStreamWriter filter(Writer writer) throws XMLStreamException {
return new NoNamesWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(writer));
}
public NoNamesWriter(XMLStreamWriter writer) {
super(writer);
}
@Override
public NamespaceContext getNamespaceContext() {
return emptyNamespaceContext;
}
}
你可以找到 DelegatingXMLStreamWriter
这里。
然后您可以使用以下方法过滤编组xml:
You can then filter the marshalling xml with:
// Filter the output to remove namespaces.
m.marshal(it, NoNamesWriter.filter(writer));
我确信有更有效的机制,但我知道这个机制有效。
I am sure there are more efficient mechanisms but I know this one works.
这篇关于在JAXB编组时删除名称空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!