dom4j是一个java的XML API,类似jdom,用来读写XML文件,它性能优异、功能强大和极易使用等特点
所用jar包:dom4j-1.6.1.jar
需要解析的xml文件:people.xml
- <people city="shenzhen">
- <student name="milton" age="22"></student>
- <student name="lego" age="23"></student>
- <teacher name="bruce" age="27"></teacher>
- <teacher name="ziven" age="28"></teacher>
- </people>
首先根据xml文档构建javabean
People.java
Student.java
Teacher.java
解析代码:
- package com.test.xml;
-
- import java.io.File;
- import java.net.URISyntaxException;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
-
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
-
- import com.test.xml.element.People;
- import com.test.xml.element.Student;
- import com.test.xml.element.Teacher;
-
- public class XmlParser {
- @SuppressWarnings("unchecked")
- public static People parseXml(String xmlPath){
- File xmlFile = new File(xmlPath);
- System.out.println(xmlFile.getPath());
- if(xmlFile.exists()){
- SAXReader reader = new SAXReader();
- People people = new People();
- try {
-
- Document document = reader.read(xmlFile);
-
- Element root = document.getRootElement();
-
- List<Student> students = new ArrayList<Student>();
- List<Teacher> teachers = new ArrayList<Teacher>();
- people.setCity(root.attributeValue("city"));
-
- for(Iterator iterator = root.elementIterator("student");iterator.hasNext();){
- Element eStudent = (Element) iterator.next();
- Student student = new Student(eStudent.attributeValue("name"), Integer.parseInt(eStudent.attributeValue("age")));
- students.add(student);
- }
-
- for(Iterator iterator = root.elementIterator("teacher");iterator.hasNext();){
- Element eTeacher = (Element) iterator.next();
- Teacher teacher = new Teacher(eTeacher.attributeValue("name"), Integer.parseInt(eTeacher.attributeValue("age")));
- teachers.add(teacher);
- }
- people.setStudent(students);
- people.setTeacher(teachers);
- System.out.println("parse success!");
- } catch (DocumentException e) {
- e.printStackTrace();
- }
- return people;
- }else{
- System.out.println("file is not exist!");
- return null;
- }
- }
-
- public static void main(String[] args) throws URISyntaxException{
- String xmlPath = "";
- xmlPath = "D:/Program Files/eclipse-jee/workspace/TEST/src/com/test/xml/people.xml";
- System.out.println("file full path is "+xmlPath);
-
- People p = parseXml(xmlPath);
-
-
- System.out.println(p.getCity());
- List<Student> sList = p.getStudent();
- List<Teacher> tList = p.getTeacher();
- for(Student s:sList){
- System.out.println(s.getName()+"--"+s.getAge());
- }
- for(Teacher t:tList){
- System.out.println();
- }
- }
- }
- parse success!
- shenzhen
- milton--22
- lego--23
dom4j解析xml实例,布布扣,bubuko.com
dom4j解析xml实例
原文:http://www.cnblogs.com/henuyuxiang/p/3874894.html