Home > front end >  How to remove XML namespace in Java
How to remove XML namespace in Java

Time:10-03

I need to remove the namespace from an XML using Java (the project also makes use of SAX/JAXB). The example below illustrates what is needed, essentially to transform the input XML into the result XML. Any advice / working example of how this can be achieved?

Input XML:

<ns2:client xmlns:ns2="http://my-org/schemas" instance="1">

        <ns2:dob>1969-01-01T00:00:00</ns2:dob>

        <ns2:firstname>Anna</ns2:firstname>

        <ns2:married>false</ns2:married>

        <ns2:gender>Female</ns2:gender>

        <ns2:surname>Smith</ns2:surname>

        <ns2:title>Miss</ns2:title>

</ns2:client>

Result XML:

<client instance="1">

        <dob>1969-01-01T00:00:00</dob>

        <firstname>Anna</firstname>

        <married>false</married>

        <gender>Female</gender>

        <surname>Smith</surname>

        <title>Miss</title>

</client>

CodePudding user response:

This is a fairly common question, and a quick search turned up the following questions:

How do I remove namespaces from xml, using java dom?

Remove namespace from XML in Java

Perssonally, I think XSLT is the most obvious technique because this is exactly what XSLT was invented for ( XML-to-XML tranformations). I have successfully used this XSLT to strip namespaces (credit goes to https://stackoverflow.com/users/18771/tomalak):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="node()">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*" />
    </xsl:copy>
  </xsl:template>

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

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

You will find the Java code for executing that XSLT in both threads.

  • Related