我需要解析具有相同标签名称的 XML 文档。我给你一个这段代码的例子,看看我想做什么。
<SystemData>
<SystemName>xmlexample</SystemName>
<Schools>
<School>
<SchoolName>SCHOOL1</SchoolName>
<Classes>
<Class>
<ClassName>ACLASS</ClassName>
</Class>
</Classes>
<Classes>
<Class>
<ClassName>BCLASS</ClassName>
</Class>
</Classes>
</School>
<School>
<SchoolName>SCHOOL2</SchoolName>
<Classes>
<Class>
<ClassName>CCLASS</ClassName>
</Class>
</Classes>
</School>
</Schools>
</SystemData>
我想要的结果是:
SCHOOL1
ACLASS
BCLASS
SCHOOL2
CCLASS
我正在尝试使用 for 循环,但它让我为每所学校的所有课程都提供了帮助。
到目前为止我的代码:
NodeList schoolist = doc.getElementsByTagName("School");
int num = schoolist.getLength();
for (int temp = 0; temp < num; temp++) {
Node nNode = schoolist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) schoolist.item(temp);
Node schoolname = eElement.getFirstChild();
System.out.println("schoolname: " + eElement.getElementsByTagName("ClassName").item(0).getTextContent());
}
NodeList Classlist = doc.getElementsByTagName("Method");
int num1 = Classlist.getLength();
for (int i = 0; i < num1; i++) {
Node nNode1 = Classlist.item(i);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) Classlist.item(i);
Node Classname = eElement1.getFirstChild();
System.out.println("Classname: " + eElement1.getElementsByTagName("ClassName").item(0).getTextContent());
}
}
}