remove xmlns attribute from the root element while

2019-03-29 10:34发布

问题:

This might be a related to JAXB Marshaller - How do I suppress xmlns namespace attributes?

But my problem is a little different. I do the regular java marshalling and my xsd has no namespaces.The generated xml is without namespaces as well, except for the root element.

<?xml version="1.0" encoding="UTF-8"?><rootElement xmlns:ns2="unwanted namespace">

The unwanted namespace is from another schema from the same project and I am not sure why that is being picked up at this stage.

My rootElement.java generated by jaxb2-maven-plugin looks like :

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"feed"
})
@XmlRootElement(name = "rootElement", namespace = "")
public class RootElement{
....
}

At this point all I want is to get rid of the xmlns:ns2="unwanted namespace" attribute from the generated xml and I am struggling with it.

I looked at my package-info.java and it looks like:

@javax.xml.bind.annotation.XmlSchema(namespace = "unwanted namespace", elementFormDefault =   javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mypackage;

I tried adding he -npa but it wont work on jaxb2-maven-plugin for some reason. I tried the NamespaceMapper but that works for changing prefixes. I could not get it to remove the namespace altogether. This is bothering me for a day now.

回答1:

I have similar requirements at the moment. The only solution that worked for me is implementing a wrapper for XMLStreamWriter.

Please, take a look at my answer here. I've also described there other solutions I tried out.

Serialization using code from the link above looks like this:

XMLOutputFactory factory = XMLOutputFactory.newFactory();

StringWriter writer = new StringWriter(XML_BUFFER_INITIAL_SIZE);
XMLStreamWriter xmlWriter = null;

try {
  xmlWriter = factory.createXMLStreamWriter(writer);
  JAXBContext context = JAXBContext.newInstance(MyJAXBGeneratedClass.class);
  Marshaller marshaller = context.createMarshaller();
  marshaller.marshal(reportContainer, new NamespaceStrippingXMLStreamWriter(xmlWriter));
  xmlWriter.flush();
}
finally {
  if (xmlWriter != null)
    xmlWriter.close();
}

return writer.toString();