我有文件XML文件,我想读取这个文件,但我想使用循环" FOR"用于读取元素。 不是:我使用" org.w3c.dom" 文件XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Labels>
<xLabel>
<NamexLabel>wer</NamexLabel>
<NamexLabel>we</NamexLabel>
<NamexLabel>sdf</NamexLabel>
</xLabel>
<yLabel>
<NameyLabel>1sa</NameyLabel>
<NameyLabel>2as</NameyLabel>
<NameyLabel>3as</NameyLabel>
</yLabel>
</Labels>
我需要阅读此文件,但我无法通过循环访问&#34; yLabel&#34;中的所有元素。和&#34; xLabel&#34;。
代码java:
File xmlfile = new File("D:\\Project//createFile.xml");
DocumentBuilderFactory documentFactory =DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlfile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("xLabel");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element student = (Element) node;
System.out.println(" Name : " + student.getElementsByTagName("NamexLabel").item(0).getTextContent());
}
}
nodeList = doc.getElementsByTagName("yLabel");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
Element student = (Element) node;
*******//I change get Elemets to loop For****
System.out.println(" Name : " + student.getElementsByTagName("NameyLabel").item(0).getTextContent());
System.out.println(" Name : " + student.getElementsByTagName("NameyLabel").item(1).getTextContent());
System.out.println(" Name : " + student.getElementsByTagName("NameyLabel").item(2).getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
使用:
NodeList nodeList = doc.getElementsByTagName("xLabel");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Node node = nodeList.item(temp);
NodeList namexLabelNodes = node.getChildNodes();
for (int i = 0; i < namexLabelNodes.getLength(); i++) {
System.out.println(" Name : " + namexLabelNodes.item(i).getTextContent());
}
}
对于yLabel将是相同的代码。