欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

dom4j解析xml

程序员文章站 2022-03-03 13:02:54
...
import org.dom4j.io.SAXReader;

//使用dom4j解析xml
public class Dom4j {

private List<Person> bookList = null;
private Person book = null;

public List<Person> getPersons(File file){
SAXReader reader = new SAXReader();
try {
Document document = reader.read(file);
Element bookstore = document.getRootElement();
Iterator storeit = bookstore.elementIterator();

bookList = new ArrayList<Person>();
while(storeit.hasNext()){
book = new Person();
Element bookElement = (Element) storeit.next();
//遍历bookElement的属性  
List<Attribute> attributes = bookElement.attributes();
for(Attribute attribute : attributes){
if(attribute.getName().equals("id")){
String id = attribute.getValue();
book.setId(id);
}
}
Iterator bookit = bookElement.elementIterator();
while(bookit.hasNext()){
Element child = (Element) bookit.next();
String nodeName = child.getName();
if(nodeName.equals("name")){
String name = child.getStringValue();
book.setName(name);
}else if(nodeName.equals("email")){
String email = child.getStringValue();
book.setEmail(email);
}
}
bookList.add(book);
book = null;
}
}catch(DocumentException e){
e.printStackTrace();
}
return bookList;
}

public static void main(String[] args) {
long s = System.currentTimeMillis();
File file = new File("persons.xml");
List<Person> bookList = new Dom4j().getPersons(file);
for(Person book : bookList){
System.out.println(book);
}
long o = System.currentTimeMillis();
System.out.println(o-s);
}
}
相关标签: xml