import org.w3c.dom.*; import org.apache.xerces.parsers.DOMParser; class Grades { static float grades[][] = new float[100][5]; static int nstudent = 0; static int gi = -1; public static void computeGrades(String uri) { try { DOMParser parser = new DOMParser(); parser.parse(uri); Document doc = parser.getDocument(); traverse_tree(doc); compute_final_grades(); } catch (Exception e) { e.printStackTrace(System.err); } } private static void compute_final_grades() { float Ave = 0; int i = 0, j = 0; System.out.println("Grades"); for(i = 0; i < nstudent ; i++) { float total = 0; for(j = 0; j < 4; j++) { total += grades[i][j]; } grades[i][4] = total/4; Ave += grades[i][4]; System.out.println("Student " + i + "=" + grades[i][4]); } Ave /= nstudent; System.out.println("Class Average =" + Ave); } private static void traverse_tree(Node node) { if(node == null) { return; } int type = node.getNodeType(); switch (type) { case Node.DOCUMENT_NODE: { traverse_tree(((Document)node).getDocumentElement()); break; } case Node.ELEMENT_NODE: { String elementName = node.getNodeName(); gi = -1; if(elementName.equals("hw1")) gi = 0; else if(elementName.equals("hw2")) gi = 1; else if(elementName.equals("project")) gi = 2; else if(elementName.equals("final")) gi = 3; else if(elementName.equals("student")) nstudent++; NodeList childNodes = node.getChildNodes(); if(childNodes != null) { int length = childNodes.getLength(); for (int loopIndex = 0; loopIndex < length ; loopIndex++) { traverse_tree(childNodes.item(loopIndex)); } } break; } case Node.TEXT_NODE: { String chData = node.getNodeValue().trim(); if(chData.indexOf("\n") < 0 && chData.length() > 0) { if(gi >= 0) grades[nstudent-1][gi] = Integer.parseInt(chData); } } } } } public class DOMGrades { public static void main(String[] args) { Grades.computeGrades(args[0]); } } ------------------------------------------------------------------------ Programming XML in Java John Punin John Smith 30 70 80 85 George Lucas 80 90 100 40 Elizabeth Roberts 60 95 50 90