所以,我有这个 xml 文件:
<Network id="TestSet01" description="Simple test set to begin development">
<node_list>
<node id="n0"/>
<node id="n1"/>
<node id="n2"/>
</node_list>
</Network>
我有这个代码:
try {
File inputFile = new File("TestSet01_Network.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList rList = doc.getElementsByTagName("Network");
for (int h = 0; h < rList.getLength(); h++) {
Node rNode = rList.item(h);
String name = ((Element) rNode).getAttribute("id");
String description = ((Element) rNode).getAttribute("description");
NodeList nList = ((Element) rNode).getElementsByTagName("node_list"); //Doesn't work properly here
for (int i = 0; i < nList.getLength(); i++) {
//code
}
} catch (ParserConfigurationException | SAXException | IOException e) {
}
我遇到的问题是,我似乎无法获取包含“node_list”节点的子节点的 NodeList,因此我可以在之后的“for”循环中单独迭代它们。代码似乎是正确的,但列表不正确。我标记了遇到此问题的行。
最佳答案
NodeList rList = doc.getElementsByTagName("Network");
将返回包含 1 个子项的列表:...
节点实际上是它的子节点 所以你只需要在开始循环之前再深入一层
Element root = doc.getDocumentElement(); //Network
for (int i = 0; i < root.getChildNodes().getLength(); i++) {
Node n = root.getChildNodes().item(i);
if (n instanceof Element) {
NodeList nodes = n.getChildNodes();
for (int j = 0; j < nodes.getLength(); j++) {
Node theNode = nodes.item(j);
if (theNode instanceof Element) {
System.out.println(((Element) theNode).getAttribute("id"));
}
}
}
}
关于java - 无法从 java xml 解析器中的当前节点获取 NodeList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275640/