DOM4J
解析实例:
public class Dom4jParser {
private static ArrayList<Book> booksList = new ArrayList<>();
public static void main(String[] args) {
Book bookEn=null;
//创建SAXReader对象reader
SAXReader reader = new SAXReader();
try {
//通过reader对象的read方法加载book.xml文件,获取document对象
Document document = reader.read(new File("books.xml"));
//通过Element对象获取根节点
Element root = document.getRootElement();
//遍历迭代器,获取根节点的中的信息
Iterator<Element> it = root.elementIterator();
while(it.hasNext()){
bookEn = new Book();
System.out.println("======开始遍历======");
Element book = it.next();
//获取book的属性名和属性值
List<Attribute> bookAttrs = book.attributes();
for (Attribute attr : bookAttrs) {
System.out.println("属性名:"+attr.getName()+"--属性值:"+attr.getValue());
if(attr.getName().equals("id")){
bookEn.setId(attr.getValue());
}
}
//book的节点迭代器
Iterator<Element> itBook = book.elementIterator();
while(itBook.hasNext()){
Element child = itBook.next();
System.out.println("节点名:"+child.getName()+"--节点值:"+child.getStringValue());
if(child.getName().equals("name")){
bookEn.setName(child.getStringValue());
}else if(child.getName().equals("author")){
bookEn.setAuthor(child.getStringValue());
}else if(child.getName().equals("year")){
bookEn.setYear(child.getStringValue());
}else if(child.getName().equals("price")){
bookEn.setPrice(child.getStringValue());
}else if(child.getName().equals("language")){
bookEn.setLanguage(child.getStringValue());
}
}
System.out.println(bookEn);
booksList.add(bookEn);
bookEn = null;
System.out.println(booksList.size());
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}