所以,我有这个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”循环中单独迭代它们。代码似乎是正确的,但列表不对。我标记了我遇到这个问题的路线。
答案 0 :(得分:1)
NodeList rList = doc.getElementsByTagName("Network");
将返回包含1个孩子的List:...
节点实际上是它的孩子 所以你只需要在开始循环之前更深一层
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"));
}
}
}
}