dom4j 解析XML很方便,很容易理解,废话少说,直接看代码。

XML文件,3层的,比较简单:

<?xml version="1.0" encoding="utf-8" ?>
<employees>
<employee empid="281033" ID="1" >
<name>Leon </name>
<birthDate>1989-12-02</birthDate>
<hireDate>2011-04-18</hireDate>
<appartment>Insurance</appartment>
<salary>3500</salary>
<leaderId>186903</leaderId>
</employee>
<employee empid="281036" ID="2">
<name>Sam</name>
<birthDate>1988-12-02</birthDate>
<hireDate>2011-04-18</hireDate>
<appartment>Financial</appartment>
<salary>3500</salary>
<leaderId>186903</leaderId>
</employee>
<employee empid="186903" ID="3">
<name>Mike</name>
<birthDate>1978-12-02</birthDate>
<hireDate>2009-04-18</hireDate>
<appartment>Insurance</appartment>
<salary>10000</salary>
<leaderId>181911</leaderId>
</employee>
</employees>


JavaBean:

package leon.tool;

import java.util.Date;

public class Employee implements Comparable{
private String Id;
private String name;
private Date birthDate;
private Date hireDate;
private String appartment;
private int salary;
private String leaderId;

//constructor
public Employee(){}
public Employee(String id){
this.Id = id;
}

//getter and setter
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getAppartment() {
return appartment;
}
public void setAppartment(String appartment) {
this.appartment = appartment;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getLeaderId() {
return leaderId;
}
public void setLeaderId(String leaderId) {
this.leaderId = leaderId;
}

@Override
public int compareTo(Object o) {
Employee e = (Employee) o;
return this.Id.compareTo(e.Id);
}
public boolean equals(Object o){
Employee e = (Employee) o;
return this.Id.equals(e.Id);
}
public String toString(){
return this.Id+"\t"+this.name+"\t"+this.salary+"\t"+this.appartment;
}
}


解析操作的主要类:

package leon.tool;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jXMLReader {
public static String XML_FILE_NAME = "employee.xml";
public static File XML_FILE;
static{
XML_FILE = new File(XML_FILE_NAME);
}

public static List<Employee> parseXMLForEmployeeList(File xmlFile){
List<Employee> employeeList = new ArrayList<Employee>();
SAXReader saxReader = new SAXReader();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Document doc = saxReader.read(xmlFile);
Element rootElement = doc.getRootElement();

for(Iterator iter = rootElement.elementIterator();iter.hasNext();){
Element element = (Element) iter.next();
String id = element.attributeValue("empid");
Employee emp = new Employee(id);

/*get value method 1*/
String name = element.element("name").getTextTrim();
String leaderId = element.element("leaderId").getTextTrim();
String appartment = element.element("appartment").getTextTrim();
String birthDateStr = element.element("birthDate").getTextTrim();
String hireDateStr = element.element("hireDate").getTextTrim();
String salaryStr = element.element("salary").getTextTrim();
emp.setName(name);
emp.setLeaderId(leaderId);
emp.setAppartment(appartment);
emp.setBirthDate(sdf.parse(birthDateStr));
emp.setHireDate(sdf.parse(hireDateStr));
emp.setSalary(Integer.parseInt(salaryStr));

/* get value method 2
for(Iterator innerIter = element.elementIterator();innerIter.hasNext();){
Element e = (Element) innerIter.next();
if("name".equalsIgnoreCase(e.getName())){
emp.setName(e.getTextTrim());
}else if("birthDate".equalsIgnoreCase(e.getName())){
emp.setBirthDate(sdf.parse(e.getTextTrim()));
}else if("hireDate".equalsIgnoreCase(e.getName())){
emp.setHireDate(sdf.parse(e.getTextTrim()));
}else if("salary".equalsIgnoreCase(e.getName())){
emp.setSalary(Integer.parseInt(e.getTextTrim()));
}else if("appartment".equalsIgnoreCase(e.getName())){
emp.setAppartment(e.getTextTrim());
}else if("leaderId".equalsIgnoreCase(e.getName())){
emp.setLeaderId(e.getTextTrim());
}
}
*/
employeeList.add(emp);
}

} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

return employeeList;
}

public static Map<String,Employee> parseXMLForEmployeeMap(File xmlFile){
Map<String,Employee> employeeMap = new HashMap<String,Employee>();
SAXReader saxReader = new SAXReader();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Document doc = saxReader.read(xmlFile);
Element rootElement = doc.getRootElement();
for(Iterator iter = rootElement.elementIterator();iter.hasNext();){
Element element = (Element) iter.next();
String empId = element.attributeValue("empid");
Employee emp = elementToEmployee(element);
employeeMap.put(empId, emp);
}

} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

return employeeMap;
}

public static Employee getEmployeeById(String empId){
Employee emp = null;
SAXReader saxReader = new SAXReader();

try {
Document doc = saxReader.read(XML_FILE);
Element rootElement = doc.getRootElement();
Element empElement = rootElement.elementByID(empId);
emp = elementToEmployee(empElement);
} catch (DocumentException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

return emp;
}

public static Employee elementToEmployee(Element e) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String id = e.attributeValue("empid");
Employee emp = new Employee(id);

String name = e.element("name").getTextTrim();
String leaderId = e.element("leaderId").getTextTrim();
String appartment = e.element("appartment").getTextTrim();
String birthDateStr = e.element("birthDate").getTextTrim();
String hireDateStr = e.element("hireDate").getTextTrim();
String salaryStr = e.element("salary").getTextTrim();

emp.setName(name);
emp.setLeaderId(leaderId);
emp.setAppartment(appartment);
emp.setBirthDate(sdf.parse(birthDateStr));
emp.setHireDate(sdf.parse(hireDateStr));
emp.setSalary(Integer.parseInt(salaryStr));

return emp;
}

}


简单的使用main方法跑跑看:

package leon.tool;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class TestXMLEmployee {

public static void main(String[] args) {
File f = new File("employee.xml");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> empList = Dom4jXMLReader.parseXMLForEmployeeList(f);

Collections.sort(empList);

for(Employee e : empList){
System.out.println(e+"\t"+e.getLeaderId()+"\t"+sdf.format(e.getHireDate()));
}

Employee emp = Dom4jXMLReader.getEmployeeById("1");
System.out.println(emp);

Map<String,Employee> employeeMap = Dom4jXMLReader.parseXMLForEmployeeMap(f);
System.out.println(employeeMap.get("281036"));
}

}


用elementById方法时,要求XML中节点有大写的ID属性。