How to Remove Namespace from XML using XSLT

In this tutorial we will see how to remove namespace from XML using XSLT. As the title suggests we will use here XSLT to remove namespace from XML. Removing namespaces from an XML document is not recommended and is in essence comparable to removing namespaces from a programming framework or library. It may risk name clashes and lose the ability to differentiate between distinct elements. But if you need to absolutely remove for some reason then consider to remove namespace from XML using XSLT.

You would also like to read similar tutorial Transforming XML to HTML using XSLT

Prerequisites

Knowledge of XML

Now we will see the actual example to remove namespace from XML using XSLT and for that please go through the following instructions in order to create project in Eclipse and remove namespace XML using XSLT.

Please follow the steps 1 and step 2 from tutorial Transforming XML to HTML using XSLT  to create the project in Eclipse.

Next create the XSLT file called Xslt2Xml.xsl and put it under src/main/resources/xslt directory. Here the standard format of XSLT is to keep everything inside the tag

<?xml version="1.0" encoding="UTF-8"?>
<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:copy>
			<xsl:apply-templates select="node() | @*" />
		</xsl:copy>
	</xsl:template>
</xsl:stylesheet>

We are writing below Java class to transform the XML file to remove namespace from XML using XSLT file. We have put both XML and XSLT files under classpath and finally transform to the XML string as an output. This is also called XML to XML transformation but the final XML does not contain any namespace.

package com.jeejava.transform;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class NamespaceRemover {
	public String remove() throws SAXException, IOException, ParserConfigurationException,
						TransformerFactoryConfigurationError, TransformerException {
						
		InputStream xmlData = getClass().getClassLoader().getResourceAsStream("xml/sample.xml");
		URL xsltURL = getClass().getClassLoader().getResource("xslt/Xslt2Xml.xsl");
		Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlData);
		Source stylesource = new StreamSource(xsltURL.openStream(), xsltURL.toExternalForm());
		Transformer transformer = TransformerFactory.newInstance().newTransformer(stylesource);
		StringWriter stringWriter = new StringWriter();
		transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter));
		
		return stringWriter.toString();
	}
}

In order to test the application create below main class. Here we have Java’s built-in logger class to log the output into Eclipse console.

package com.jeejava.main;
import java.io.IOException;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactoryConfigurationError;
import org.xml.sax.SAXException;
import com.jeejava.transform.NamespaceRemover;
public class RemoveNamespaceTest {
	static final Logger LOGGER = Logger.getLogger(RemoveNamespaceTest.class.getName());
	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException,
						TransformerFactoryConfigurationError, TransformerException {
		NamespaceRemover remover = new NamespaceRemover();
		String resp = remover.remove();
		LOGGER.info(resp);
	}
}

Run the main class, you will see the XML output completely removing namespace.

Here is the src/main/resources/xml/sample.xml file from which we need to remove namespace using xslt.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <ns2:getUserDetailsResponse xmlns:ns2="http://www.jeejava.com/UserService">
         <ns2:users>
            <ns2:id>4</ns2:id>
            <ns2:name>Liton Sarkar</ns2:name>
            <ns2:email>liton.sarkar@email.com</ns2:email>
            <ns2:address>
               <ns2:street>Sukanta Nagar</ns2:street>
               <ns2:city>Kolkata</ns2:city>
               <ns2:state>WB</ns2:state>
               <ns2:zip>700098</ns2:zip>
               <ns2:country>India</ns2:country>
               <ns2:addressType>COMMUNICATION</ns2:addressType>
            </ns2:address>
         </ns2:users>
      </ns2:getUserDetailsResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

After removing namespace from above xml file, the final output is given below. You will find this output in the Eclipse console. If you want to write this output to some XML file then you can check the tutorial Transforming XML to HTML using XSLT, where how we had written HTML output to a file.

<?xml version="1.0" encoding="UTF-8"?><Envelope>
   <Header/>
   <Body>
      <getUserDetailsResponse>
         <users>
            <id>4</id>
            <name>Liton Sarkar</name>
            <email>liton.sarkar@email.com</email>
            <address>
               <street>Sukanta Nagar</street>
               <city>Kolkata</city>
               <state>WB</state>
               <zip>700098</zip>
               <country>India</country>
               <addressType>COMMUNICATION</addressType>
            </address>
         </users>
      </getUserDetailsResponse>
   </Body>
</Envelope>

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *