java解析xml之dom4j解析xml示例分享
package com.test;
import java.io.file;
import java.util.arraylist;
import java.util.iterator;
import java.util.list;
import org.dom4j.document;
import org.dom4j.element;
import org.dom4j.io.saxreader;
public class dom4jxml {
public static void main(string[] args) {
saxreader saxreader = new saxreader();
file file = new file("e:/people.xml");
try {
document document = saxreader.read(file);
element root = document.getrootelement();
list<people> peoples = new arraylist<people>();
for (iterator iterator = root.elementiterator(); iterator.hasnext();) {
people people = new people();
element peopleelement = (element) iterator.next();
people.setid(peopleelement.attribute("id").getvalue());
for (iterator childiterator = peopleelement.elementiterator(); childiterator.hasnext();) {
element childpeopleelement = (element) childiterator.next();
if (childpeopleelement.getname().equals("name")) {
people.setenglishname(childpeopleelement.attribute("en").getvalue());
people.setname(childpeopleelement.gettext());
} else if (childpeopleelement.getname().equals("age")) {
people.setage(childpeopleelement.gettext());
}
}
peoples.add(people);
}
for (people p : peoples) {
system.out.println(p.getid()+"\t"+p.getname()+"\t"+p.getenglishname()+"\t"+p.getage());
}
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}