package com.amos.dom4j;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4jtest {
public static void main(String[] args) throws IOException {
Book shu = null;
int j = 0;
ArrayList<Book> booklist = new ArrayList<>();
SAXReader reader = new SAXReader();
try {
Document document = reader.read(new File("src/res/books.xml"));
Element bookstore = document.getRootElement();
Iterator it = bookstore.elementIterator();
while (it.hasNext()) {
j++;
shu=null;
shu = new Book();
System.out.println("=======开始遍历第" + j + "本书==========");
Element book = (Element) it.next();
List<Attribute> shuxing = book.attributes();
for (Attribute attribute : shuxing) {
System.out.print("属性名:" + attribute.getName());
System.out.println("---值为:" + attribute.getValue());
if (attribute.getName().equals("id")) {
shu.setId(attribute.getValue());
}
Iterator its = book.elementIterator();
while (its.hasNext()) {
Element bookchild = (Element) its.next();
System.out.print("子节点名:" + bookchild.getName());
System.out.println("---值为:" + bookchild.getStringValue());
if (bookchild.getName().equals("author")) {
shu.setAuthor(bookchild.getStringValue());
}else if(bookchild.getName().equals("name")){
shu.setName(bookchild.getStringValue());
}else if(bookchild.getName().equals("price")){
shu.setPrice(bookchild.getStringValue());
}else if(bookchild.getName().equals("page")){
shu.setPage(bookchild.getStringValue());
}else if(bookchild.getName().equals("language")){
shu.setLanguage(bookchild.getStringValue());
}
}
booklist.add(shu);
}
System.out.println("=======结束遍历第" + j + "本书==========");
System.out.println();
System.out.println();
System.out.println(booklist.size());
System.out.println();
System.out.println(booklist.get(1).getAuthor());
System.out.println(booklist.get(1).getId());
System.out.println(booklist.get(1).getLanguage());
System.out.println(booklist.get(1).getName());
System.out.println(booklist.get(1).getPage());
System.out.println(booklist.get(1).getPrice());
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}