dom4j解析xml实例

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"));
				//解析student节点
				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);
				}
				//解析teacher节点
				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.xml
		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

你可能感兴趣的:(java,eclipse,xml,.net)