How to remove all namespaces from a dom document

I am creating a Dom document (org.w3c.dom.Document) from an XML file. I want to remove the entire namespace from this document in order to call another service. This service expects XML without a namespace.

+4
source share
1 answer
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;
        for (!(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);
    }
}
+4
source

All Articles