JDOM4J读XML

来源:互联网 发布:华为防火墙开放端口 编辑:程序博客网 时间:2024/05/17 07:55

1.books.xml

<?xml version="1.0" encoding="UTF-8"?><bookstore>    <book id="1">        <name>冰与火之歌</name>        <author>乔治马丁</author>        <year>2014</year>        <price>89</price>    </book>    <book id="2">        <name>安徒生童话</name>        <year>2004</year>        <price>77</price>        <language>English</language>    </book> </bookstore>

2.DOM4JTest
(1)解析根节点中的所有信息

// 创建SAXReader的对象reader        SAXReader reader = new SAXReader();        try {            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。            Document document = reader.read(new File("src/res/books.xml"));            // 通过document对象获取根节点bookstore            Element bookStore = document.getRootElement();            // 通过element对象的elementIterator方法获取迭代器            //迭代器里面有根节点里面的所有信息            Iterator it = bookStore.elementIterator();

(2)解析根节点中的属性(id=1)

// 遍历迭代器,获取根节点中的信息(书籍)            while (it.hasNext()) {                System.out.println("=====开始遍历某一本书=====");                //it.next返回的是object类型,所以需要强制转化为Element                Element book = (Element) it.next();                // 获取该book的属性名以及 属性值                List<Attribute> bookAttrs = book.attributes();                for (Attribute attr : bookAttrs) {                    System.out.println("属性名:" + attr.getName() + "--属性值:"                            + attr.getValue());                }

(3)解析子节点中的信息(节点名和节点值比如name price之类的)

Iterator itt = book.elementIterator();                while (itt.hasNext()) {                    Element bookChild = (Element) itt.next();                    System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue());                }                System.out.println("=====结束遍历某一本书=====");            }        } catch (DocumentException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}