Вот пример моих новых XML-файлов (я изменил названия тегов, чтобы было легче понять):
Код: Выделить всё
John
14
A
B
A+
Tom
13
A
incomplete
Код: Выделить всё
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;
}
Подробнее здесь: https://stackoverflow.com/questions/112 ... es-in-java