0
votes

I am trying to remove namespace prefix while unmarshalling, I was able to change the namespace using PrefixMapper by setting marshaller property. Default namespace is ns2, I don't want any prefix, but it is not allowing me to give empty prefix value. If I give empty string as below it is taking default value.

1) jaxbMarshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new MyNamespaceMapper()); .....

class MyNamespaceMapper extends NamespacePrefixMapper {
    private static final String URI = "http://www.examples/webservice/";   

    @Override
    public String getPreferredPrefix(String namespaceUri, String suggestion, 
      boolean requirePrefix) {
        if(URI.equals(namespaceUri)) {
            return "";
        }
        return suggestion;
    }
}

2) If I edit package-info as below then it is fine, but issue is that I am creating one JAXB Integer Element as below, prefix removal is not applying on these elements

JAXBElement<Integer> jaxBInteger = new JAXBElement<Integer>(
                            new QName("http://www.example.com/", "age",""),30);
                    pax.setAge(jaxBInteger);

<Login Password="" Email=""/>
        <Paxes>
            <Pax IdPax="1">
                <ns2:Age>30</ns2:Age>
            </Pax>
            <Pax IdPax="2">
                <ns2:Age>30</ns2:Age>
            </Pax>
        </Paxes>
    </Login>
1

1 Answers

1
votes

yes replacing prefix as "empty" seems very tricky as you can see my question here. I did find the solution to do transformation using xslt after the XML generation as below. Hope it helps.

removenamespace.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
     <xsl:preserve-space elements="*"/>

    <xsl:template match="@*|node()[not(self::*)]">
        <xsl:copy />
    </xsl:template>

    <xsl:template match="*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()|@*" />
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

XSLT transformer

    File outputXML = new File(inputXML.getParentFile(), inputXML.getName() + "-ns.xml");

    try{ 
    TransformerFactory factory = TransformerFactory.newInstance();
    Source xslt = new StreamSource(new File(REMOVE_NAMESPACE_XSL));
    Transformer transformer = factory.newTransformer(xslt);

    Source text = new StreamSource(inputXML);
    transformer.transform(text, new StreamResult(outputXML));

    }
    catch(Exception e){
        // something gone wrong. return original XML.
        return inputXML;
    }