Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove xmlns attribute from the root element in xml and java

Tags:

java

xml

stax

I would like to remove the xmlns attribute from following xml string. I have written a java program but not sure if it does what needs to be done here.

How do I remove the xmlns attribute and get the modified xml string ?

Input XML string:

<?xml version="1.0" encoding="UTF-8"?>
<Payment xmlns="http://api.com/schema/store/1.0">
    <Store>abc</Store>
</Payment>

Expected XML Output string:

<?xml version="1.0" encoding="UTF-8"?>
<Payment>
    <Store>abc</Store>
</Payment>

Java Class:

public class XPathUtils {

    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>";
        String afterNsRemoval = removeNameSpace(xml);
        System.out.println("afterNsRemoval = " + afterNsRemoval);
    }

    public static String removeNameSpace(String xml) {
        try {
            System.out.println("before xml = " + xml);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document xmlDoc = builder.parse(inputSource);
            Node root = xmlDoc.getDocumentElement();
            NodeList rootchildren = root.getChildNodes();
            Element newroot = xmlDoc.createElement(root.getNodeName());
            for (int i = 0; i < rootchildren.getLength(); i++) {
                newroot.appendChild(rootchildren.item(i).cloneNode(true));
            }
            xmlDoc.replaceChild(newroot, root);
            return xmlDoc.toString();
        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
        return "";
    }
}

Output:

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>

afterNsRemoval = [#document: null]
like image 579
Nital Avatar asked May 20 '16 19:05

Nital


3 Answers

You need a transformer. Check below the modified method :

public static String removeNameSpace(String xml) {


        try {
             TransformerFactory tf = TransformerFactory.newInstance();
             Transformer transformer = tf.newTransformer();
             transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
             transformer.setOutputProperty( OutputKeys.INDENT, "false" );
            System.out.println("before xml = " + xml);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource inputSource = new InputSource(new StringReader(xml));
            Document xmlDoc = builder.parse(inputSource);
            Node root = xmlDoc.getDocumentElement();
            NodeList rootchildren = root.getChildNodes();
            Element newroot = xmlDoc.createElement(root.getNodeName());
            for (int i = 0; i < rootchildren.getLength(); i++) {
                newroot.appendChild(rootchildren.item(i).cloneNode(true));
            }
            xmlDoc.replaceChild(newroot, root);
            DOMSource requestXMLSource = new DOMSource( xmlDoc.getDocumentElement() );
            StringWriter requestXMLStringWriter = new StringWriter();
            StreamResult requestXMLStreamResult = new StreamResult( requestXMLStringWriter );            
            transformer.transform( requestXMLSource, requestXMLStreamResult );
            String modifiedRequestXML = requestXMLStringWriter.toString();

            return modifiedRequestXML;
        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
        return "";
    }

Output :

before xml = <?xml version="1.0" encoding="UTF-8"?><Payment xmlns="http://api.com/schema/store/1.0"><Store>abc</Store></Payment>
afterNsRemoval = <?xml version="1.0" encoding="UTF-8"?><Payment><Store>abc</Store></Payment>
like image 148
SomeDude Avatar answered Oct 08 '22 18:10

SomeDude


Consider XSLT as removing declared/undeclared namespace is a regular task. Here, no third-party modules are needed as base Java is equipped with an XSLT 1.0 processor. Additionally, no loops or XML tags/attribs re-creation is handled as XSLT takes care of the transformation.

import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
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.InputSource;
import org.xml.sax.SAXException;

public class XPathUtils {
    public static void main(String[] args) {

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"http://api.com/schema/store/1.0\"><Store>abc</Store></Payment>";
        String afterNsRemoval = removeNameSpace(xml);
        System.out.println("afterNsRemoval = " + afterNsRemoval);
    }

    public static String removeNameSpace(String xml) {
        try{
            String xslStr = String.join("\n",
                "<xsl:transform xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">",
                "<xsl:output version=\"1.0\" encoding=\"UTF-8\" indent=\"no\"/>",
                "<xsl:strip-space elements=\"*\"/>",                          
                "  <xsl:template match=\"@*|node()\">",
                "   <xsl:element name=\"{local-name()}\">",
                "     <xsl:apply-templates select=\"@*|node()\"/>",
                "  </xsl:element>",
                "  </xsl:template>",  
                "  <xsl:template match=\"text()\">",
                "    <xsl:copy/>",
                "  </xsl:template>",                                  
                "</xsl:transform>");

            // Parse XML and Build Document
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            Document doc = db.parse (is);                      

            // Parse XSLT and Configure Transformer
            Source xslt = new StreamSource(new StringReader(xslStr));
            Transformer tf = TransformerFactory.newInstance().newTransformer(xslt);

            // Output Result to String
            DOMSource source = new DOMSource(doc);
            StringWriter outWriter = new StringWriter();
            StreamResult strresult = new StreamResult( outWriter );        
            tf.transform(source, strresult);
            StringBuffer sb = outWriter.getBuffer(); 
            String finalstring = sb.toString();

            return(finalstring);

        } catch (Exception e) {
            System.out.println("Could not parse message as xml: " + e.getMessage());
        }
            return "";    
    }
}
like image 43
Parfait Avatar answered Oct 08 '22 16:10

Parfait


You have done everything right except last action: document.toString() gives you incorrect result, because it is incorrect way of producing string xml representation of Document object. See this answer, it contains correct implementation of this method:

public static String toString(Document doc) {
    try {
        StringWriter sw = new StringWriter();
        TransformerFactory tf = TransformerFactory.newInstance();
        ...
like image 33
Andremoniy Avatar answered Oct 08 '22 18:10

Andremoniy