Remove namespace prefix while JAXB marshalling

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.

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;
  }

}

You can find a DelegatingXMLStreamWriter here.

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.

Leave a Comment