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 problem, but none of them works. I cannot modify my schema or change package-info.java. Please help
You can use the NamespacePrefixMapper extension to control the namespace prefixes for your use case. The same extension is supported by both the JAXB reference implementation and EclipseLink JAXB (MOXy).
setDefaultNamespace("") solved the issue. One more thing you have to care in order to remove the namespace prefix from the output is that everywhere you have @XmlElement ensure it does not include the namespace property like @XmlElement(name="", namespace"http://...") ; otherwise, none of solutions will work.
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
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.
For me, only changing the package-info.java class worked like a charm, exactly as zatziky stated :
package-info.java
@javax.xml.bind.annotation.XmlSchema (namespace = "http://example.com", xmlns = {@XmlNs(prefix = "", namespaceURI = "http://example.com")}, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package my.package; import javax.xml.bind.annotation.XmlNs;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With