XOM
java 利用XOM解析XML
参考:http://blog.sodhanalibrary.com/2014/09/parse-xml-using-java.html#.W0rOEjozbIU
XOM解析XML为Java对象
1student_list.xml 2 3<?xml version="1.0"?> 4<students> 5 <student> 6 <name>Sriram</name> 7 <age>2</age> 8 </student> 9 <student> 10 <name>Venkat</name> 11 <age>29</age> 12 </student> 13 <student> 14 <name>Anu</name> 15 <age>28</age> 16 </student> 17</students> 18 19package com.bethecoder.tutorials.xom.tests; 20 21import java.io.IOException; 22import java.io.InputStream; 23 24import nu.xom.Builder; 25import nu.xom.Document; 26import nu.xom.Element; 27import nu.xom.Elements; 28import nu.xom.ParsingException; 29import nu.xom.ValidityException; 30 31public class ReadXML { 32 33 /** 34 * @param args 35 * @throws IOException 36 * @throws ParsingException 37 * @throws ValidityException 38 */ 39 public static void main(String[] args) throws ValidityException, ParsingException, IOException { 40 Builder builder = new Builder(); 41 InputStream ins = ReadXML.class.getClassLoader() 42 .getResourceAsStream("student_list.xml"); 43 44 //Reads and parses the XML 45 Document doc = builder.build(ins); 46 Element root = doc.getRootElement(); 47 System.out.println("Root Node : " + root.getLocalName()); 48 49 //Get children 50 Elements students = root.getChildElements(); 51 Element nameChild = null; 52 for (int i = 0 ; i < students.size() ; i ++) { 53 System.out.println(" Child : " + students.get(i).getLocalName()); 54 55 //Get first child with tag name as 'name' 56 nameChild = students.get(i).getFirstChildElement("name"); 57 if (nameChild != null) { 58 System.out.println(" Name : " + nameChild.getValue()); 59 } 60 } 61 } 62 63}