Reading Multi-Level XML files in Java

bGvzaqte4

New Member
Until recently, the tag-structure of my XML files were fairly simple, and I have been able to parse them easily. But now I have an 'extra level' of tags within tags, and I haven't been able to solve the problem.Here is an example of my new XML files (in structure, I've changed the names of the tags to make it easier to understand):\[code\]<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>\[/code\]The important features of the XML above is that I can have multiple "course" attributes, and inside that I can have arbitrarily named tags as their children. And there can be any number of these children, which I want to read into a HashMap of "name", "value".\[code\]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;}\[/code\]The problem I'm running in to is that instead of getting that the student got an "A" in "math", they get a null in "math". (If this post is too long, I can try to find some way of shortening it.)
 
Back
Top