Java XML Dom Document getElementsByTagNameNS 返回空的 NodeList



这是我的XML文档的样子 -

    <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>

这是我的 Java 代码 -

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);
}

当tagName = "a"时,getAllNodes返回的NodeList为空。但是,如果我尝试 domDocument.getElementsByTagName(tagName),我会得到 2 个元素的预期列表。

事实证明我需要启用 dbFactory.setNamespaceAware(true);

最新更新