I’m generating XML using JAXB and need specific namespace prefixes for my XML elements. Here’s an example of the XML structure I am currently generating, where each namespace has a unique prefix:
<ns4:RequestPayload
xmlns:head="urn:iso:std:iso:20022:tech:xsd:head.001.001.03"
xmlns:doc="urn:iso:std:iso:20022:tech:xsd:admi.004.001.02"
xmlns:ns4="urn:bceao:pi:xsd:payload.1.0.0"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<head:AppHdr>
<!-- Header info -->
<head:Sgntr>
<ds:Signature>
<!-- Signature info -->
</ds:Signature>
</head:Sgntr>
</head:AppHdr>
<doc:Document>
<!-- Document info -->
</doc:Document>
</ns4:RequestPayload>
When I omit the prefix namespace declarations in my package-info.java, a default naming convention is applied, resulting in prefixes like ns1, ns2, ns3:
<ns4:RequestPayload
xmlns:ns1="urn:iso:std:iso:20022:tech:xsd:head.001.001.03"
xmlns:ns2="urn:iso:std:iso:20022:tech:xsd:admi.004.001.02"
xmlns:ns4="urn:bceao:pi:xsd:payload.1.0.0"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ns1:AppHdr>
<!-- Header info -->
<ns1:Sgntr>
<ds:Signature>
<!-- Signature info -->
</ds:Signature>
</ns1:Sgntr>
</ns1:AppHdr>
<ns2:Document>
<!-- Document info -->
</ns2:Document>
</ns4:RequestPayload>
My goal is to generate an XML without any namespace prefixes, except for the “ds” prefix for the signature elements.
I tried overriding the getPreferredPrefix method in com.sun.xml.bind.marshaller.NamespacePrefixMapper to achieve the desired namespace prefix customization. Here is my implementation:
public class CustomNamespacePrefixMapper extends NamespacePrefixMapper {
@Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
if ("http://www.w3.org/2000/09/xmldsig#".equals(namespaceUri)) {
return "ds";
}
return "";
}
}
And adding to :
JAXBContext context = JAXBContext.newInstance(EnvelopeAdmi004.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new CustomNamespacePrefixMapper());
Despite this implementation, the output XML still contains default prefixes like ns1, ns2, and ns3. I expected that my custom NamespacePrefixMapper would result in an XML with no prefixes, except for the ds prefix for the signature elements.
How can I achieve the desired XML format with only the ds prefix and no other prefixes? What am I missing in my approach? Any suggestions or insights would be greatly appreciated.
farkadi oussama is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.