且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 JAXB 编组时删除命名空间前缀

更新时间:2021-11-06 02:37:28

经过大量研究和修补,我终于设法解决了这个问题.请接受我的歉意,因为没有发布原始参考文献的链接 - 有很多,我没有做笔记 - 但这个一个肯定有用.

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.