Search code examples
javaxmldomxml-parsingxmldom

Java XML Dom Document getElementsByTagNameNS returns empty NodeList


Here's what my XML Document looks like -

    <Key1>
        <ns3:a>true</ns3:a>
        <ns3:b>1.0</ns3:b>
        <ns3:c>
            <ns3:north>13</ns3:north>
            <ns3:south>113</ns3:south>
            <ns3:west>114</ns3:west>
            <ns3:east>172</ns3:east>
        </ns3:c>
    </Key1>
    <Key2>
        <ns3:SubKey>
            <ns3:a>Hello World</ns3:a>
            <ns3:b>0.9</ns3:b>
            <ns3:c>
                <ns3:north>99</ns3:north>
                <ns3:south>17</ns3:south>
                <ns3:west>65</ns3:west>
                <ns3:east>11</ns3:east>
            </ns3:c>
        </ns3:SubKey>
    </Key2>

Here's my Java code -

private Document domDocument;
public XmlDomParser(byte[] inputByteFile) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
        domDocument = documentBuilder.parse(new ByteArrayInputStream(inputByteFile));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
}


public NodeList getAllNodesByTagName(String tagName) {
    return domDocument.getElementsByTagNameNS("*",tagName);
}

When tagName = "a", the NodeList returned by getAllNodes is empty. However, if I try domDocument.getElementsByTagName(tagName), I get the expected list of 2 elements.


Solution

  • Turns out I needed to enable dbFactory.setNamespaceAware(true);