DOM4J

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();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值