Stripping XML Namespaces with JDOM
Simplifying XML by removing complex xmlns attributes
The Problem with Namespaces
XML namespaces (e.g., <h:table xmlns:h="http://www.w3.org/TR/html4/">) are
great for preventing naming conflicts, but they can make parsing unnecessarily complicated if
you don't need them. Sometimes, you just want to treat <h:table> as
<table>.
The Solution: Recursive Removal
Using the JDOM library, you can recursively walk through the XML tree and set the namespace of
every element to Namespace.NO_NAMESPACE.
import org.jdom2.Element;
import org.jdom2.Namespace;
public void stripNamespaces(Element element) {
// 1. Remove the namespace from the current element
element.setNamespace(Namespace.NO_NAMESPACE);
// 2. Recursively process all children
for (Element child : element.getChildren()) {
stripNamespaces(child);
}
}How to Use It
Simply parse your document, get the root element, and call the helper function.
import org.jdom2.Document;
import org.jdom2.input.SAXBuilder;
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("data.xml"));
// Strip namespaces from the root down
stripNamespaces(doc.getRootElement());
// Now you can access elements without namespace prefixes!
Element root = doc.getRootElement();
System.out.println(root.getChild("MyTag").getText());
}Why Recursive?
Inheritance: In XML, child elements often inherit namespaces from their
parents. Simply removing the attribute from the root element isn't enough; you must explicitly
reset the namespace object for every single node in the tree.