Monday, June 26, 2017

Java DOM from XML is not namespace aware by default

Something which costed me a couple of headaches using getElementsByTagNameNS with a DocumentBuilderFactory from the java.xml.parsers package.

You find in the class properties:

    private boolean namespaceAware = false;

and I thought XML namespaces where the bread and butter of XML ...

So when building a DOM from an XML document you need to change the defaults of the factory like:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder docBuilder = factory.newDocumentBuilder();

No comments: