title: How to remove xmlns attribute from the root element in xml and java
body: <p>I would like to remove the <code>xmlns</code> attribute from following xml string. I have written a <code>java</code> program but not sure if it does what needs to be done here.</p>
  
  <p>How do I remove the <code>xmlns</code> attribute and get the modified xml string ?</p>
  
  <p><strong>Input XML string:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;Payment xmlns="http://api.com/schema/store/1.0"&gt;
      &lt;Store&gt;abc&lt;/Store&gt;
  &lt;/Payment&gt;
  </code></pre>
  
  <p><strong>Expected XML Output string:</strong></p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;Payment&gt;
      &lt;Store&gt;abc&lt;/Store&gt;
  &lt;/Payment&gt;
  </code></pre>
  
  <p><strong>Java Class:</strong></p>
  
  <pre><code>public class XPathUtils {
  
      public static void main(String[] args) {
          String xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;Payment xmlns=\"http://api.com/schema/store/1.0\"&gt;&lt;Store&gt;abc&lt;/Store&gt;&lt;/Payment&gt;";
          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 &lt; 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 "";
      }
  }
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>before xml = &lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;Payment xmlns="http://api.com/schema/store/1.0"&gt;&lt;Store&gt;abc&lt;/Store&gt;&lt;/Payment&gt;
  
  afterNsRemoval = [#document: null]
  </code></pre>