直到最近,我的 XML 文件的标签结构还是相当简单的。但是现在我多了一层带标签的标签,解析 XML 变得更加复杂。
这是我的新 XML 文件的示例(我更改了标签名称以使其更易于理解):
<SchoolRoster>
<Student>
<name>John</name>
<age>14</age>
<course>
<math>A</math>
<english>B</english>
</course>
<course>
<government>A+</government>
</course>
</Student>
<Student>
<name>Tom</name>
<age>13</age>
<course>
<gym>A</gym>
<geography>incomplete</geography>
</course>
</Student>
</SchoolRoster>
上述 XML 的重要特性是我可以有多个“课程”属性,并且在其中我可以有任意命名的标签作为它们的子标签。并且可以有任意数量的这些孩子,我想将它们读入“名称”、“值”的 HashMap 中。
public static TreeMap getAllSchoolRosterInformation(String fileName) {
TreeMap SchoolRoster = new TreeMap();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
NodeList studentList = docEle.getElementsByTagName("Student");
if (studentList != null && studentList.getLength() > 0) {
for (int i = 0; i < studentList.getLength(); i++) {
Student aStudent = new Student();
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("name");
aStudent.setName(nodeList.item(0).getChildNodes().item(0).getNodeValue());
nodeList = e.getElementsByTagName("age");
aStudent.setAge(Integer.parseInt(nodeList.item(0).getChildNodes().item(0).getNodeValue()));
nodeList = e.getElementsByTagName("course");
if (nodeList != null && nodeList.getLength() > 0) {
Course[] courses = new Course[nodeList.getLength()];
for (int j = 0; j < nodeList.getLength(); j++) {
Course singleCourse = new Course();
HashMap classGrades = new HashMap();
NodeList CourseNodeList = nodeList.item(j).getChildNodes();
for (int k = 0; k < CourseNodeList.getLength(); k++) {
if (CourseNodeList.item(k).getNodeType() == Node.ELEMENT_NODE && CourseNodeList != null) {
classGrades.put(CourseNodeList.item(k).getNodeName(), CourseNodeList.item(k).getNodeValue());
}
}
singleCourse.setRewards(classGrades);
Courses[j] = singleCourse;
}
aStudent.setCourses(Courses);
}
}
SchoolRoster.put(aStudent.getName(), aStudent);
}
}
} else {
System.exit(1);
}
} catch (Exception e) {
System.out.println(e);
}
return SchoolRoster;
}
我遇到的问题是,学生没有在“数学”中得到“A”,而是在“数学”中得到了一个空值。(如果这篇文章太长,我可以尝试找到一些缩短它的方法。)