XOM
java 利用XOM解析XML
参考:http://blog.sodhanalibrary.com/2014/09/parse-xml-using-java.html#.W0rOEjozbIU
XOM解析XML为Java对象
student_list.xml
<?xml version="1.0"?>
<students>
<student>
<name>Sriram</name>
<age>2</age>
</student>
<student>
<name>Venkat</name>
<age>29</age>
</student>
<student>
<name>Anu</name>
<age>28</age>
</student>
</students>
package com.bethecoder.tutorials.xom.tests;
import java.io.IOException;
import java.io.InputStream;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;
public class ReadXML {
/**
* @param args
* @throws IOException
* @throws ParsingException
* @throws ValidityException
*/
public static void main(String[] args) throws ValidityException, ParsingException, IOException {
Builder builder = new Builder();
InputStream ins = ReadXML.class.getClassLoader()
.getResourceAsStream("student_list.xml");
//Reads and parses the XML
Document doc = builder.build(ins);
Element root = doc.getRootElement();
System.out.println("Root Node : " + root.getLocalName());
//Get children
Elements students = root.getChildElements();
Element nameChild = null;
for (int i = 0 ; i < students.size() ; i ++) {
System.out.println(" Child : " + students.get(i).getLocalName());
//Get first child with tag name as 'name'
nameChild = students.get(i).getFirstChildElement("name");
if (nameChild != null) {
System.out.println(" Name : " + nameChild.getValue());
}
}
}
}