在 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屋!