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.
Asked
Active
Viewed 6,698 times
5
-
Without looking at your example: Is there any specific problem you're running into? – Davio Aug 08 '14 at 11:14
-
You can try using XSL transformation as well, check this question: http://stackoverflow.com/questions/5268182/how-to-remove-namespaces-from-xml-using-xslt – Katona Aug 08 '14 at 13:20
-
I tried with xslt, but it seems performance issue – Sreekanth P Aug 14 '14 at 11:29
2 Answers
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.

user2698962
- 21
- 3