user2325154 user2325154 - 2 years ago 445
Java Question

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

I would like to remove the

attribute from following xml string. I have written a
program but not sure if it does what needs to be done here.

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

Input XML string:

<?xml version="1.0" encoding="UTF-8"?>
<Payment xmlns="">

Expected XML Output string:

<?xml version="1.0" encoding="UTF-8"?>

Java Class:

public class XPathUtils {

public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"\"><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++) {
xmlDoc.replaceChild(newroot, root);
return xmlDoc.toString();
} catch (Exception e) {
System.out.println("Could not parse message as xml: " + e.getMessage());
return "";


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

afterNsRemoval = [#document: null]

Answer Source

This is the code to do it with XPath and vtd-xml( of which I am the author)...

import com.ximpleware.*;

public class removeAttrNode {
    public static void main(String[] s) throws VTDException, Exception{
        VTDGen vg = new VTDGen(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Payment xmlns=\"\"><Store>abc</Store></Payment>";
        vg.parse(false); // turn off namespace awareness so that 
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        XMLModifier xm = new XMLModifier(vn);
        int i=0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download