remove xmlns attribute from the root element while marshalling jaxb

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 08:09:28

问题


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();


来源:https://stackoverflow.com/questions/15796063/remove-xmlns-attribute-from-the-root-element-while-marshalling-jaxb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!