【发布时间】:2016-05-31 22:42:16
【问题描述】:
这是我的 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 个元素列表。
【问题讨论】:
-
您的 xml 格式是否具有正确的命名空间声明?
-
是的。原来我需要启用 dbFactory.setNamespaceAware(true);
标签: java xml dom xml-parsing xmldom