Remove namespace prefix while JAXB marshalling

前端 未结 5 1849
無奈伤痛
無奈伤痛 2020-11-29 05:45

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

5条回答
  •  悲哀的现实
    2020-11-29 06:30

    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.

提交回复
热议问题