package com.imooc.dom4jtest; import java.io.File; 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 { private static ArrayList<Book> Books=new ArrayList<Book>(); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SAXReader reader=new SAXReader(); try { Document document=reader.read(new File("Books.xml")); Element bookstore=document.getRootElement(); //通过element对象的elementIterator方法获取迭代器 Iterator it=bookstore.elementIterator(); while(it.hasNext()){ Book book2=new Book(); System.out.println("=====开始遍历某一本书====="); Element book=(Element) it.next(); List<Attribute>attrsList=book.attributes(); for (Attribute attribute : attrsList) { if(attribute.getName().equals("id")){ book2.setId(attribute.getValue()); } System.out.println("属性名为:"+attribute.getName()+"---属性值为:"+attribute.getValue()); } Iterator itt=book.elementIterator(); while(itt.hasNext()){ Element element=(Element) itt.next(); System.out.println("节点名为:"+element.getName()+"---节点值为:"+element.getStringValue()); if(element.getName().equals("name")){ book2.setName(element.getStringValue()); } if(element.getName().equals("author")){ book2.setAuthor(element.getStringValue()); } if(element.getName().equals("year")){ book2.setYear(element.getStringValue()); } if(element.getName().equals("language")){ book2.setLanguage(element.getStringValue()); } if(element.getName().equals("price")){ book2.setPrice(element.getStringValue()); } } Books.add(book2); book2=null; } System.out.println("=====结束遍历某一本书====="); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("共有"+Books.size()+"本书"); for (Book book : Books) { System.out.println("id:"+book.getId()); System.out.println("name:"+book.getName()); System.out.println("year:"+book.getYear()); if(book.getAuthor()!=null){ System.out.println("author:"+book.getAuthor());} if(book.getLanguage()!=null){System.out.println("language:"+book.getLanguage());} System.out.println("price:"+book.getPrice()); } } }
....