5

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.

Sreekanth P
  • 1,187
  • 2
  • 12
  • 16

2 Answers2

11
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);
    }
}
Andrew Nessin
  • 1,206
  • 2
  • 15
  • 22
Sreekanth P
  • 1,187
  • 2
  • 12
  • 16
0

If you just map.removeNamedItemNS, you can remove namespaced attributes you really need. In that case it's better to removeNamedItemNS which are n.getNamespaceURI()!=null && "xmlns".equals (n.getPrefix ()), but ownerDoc.renameNode(n,null,n.getLocalName()) for others that n.getNamespaceURI()!=null too - this will remove attribute from namespace, auto remove prefix and leave attribute in a document.