Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Remove all the namespaces from a dom Document

Tags:

java

I am creating a Dom (org.w3c.dom.Document) document from a XML File. I want to remove all the namespace from that document to invoke some other service. That service expecting an XML without name space.

like image 259
Sreekanth P Avatar asked Dec 25 '22 05:12

Sreekanth P


1 Answers

public Document cleanNameSpace(Document doc) {

    NodeList list = doc.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        removeNamSpace(list.item(i), "");
    }

    return doc;
}
private void removeNamSpace(Node node, String nameSpaceURI) {

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Document ownerDoc = node.getOwnerDocument();
        NamedNodeMap map = node.getAttributes();
        Node n;
        while (!(0==map.getLength())) {
            n = map.item(0);
            map.removeNamedItemNS(n.getNamespaceURI(), n.getLocalName());
        }
        ownerDoc.renameNode(node, nameSpaceURI, node.getLocalName());
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        removeNamSpace(list.item(i), nameSpaceURI);
    }
}
like image 151
Sreekanth P Avatar answered Dec 28 '22 07:12

Sreekanth P