Java眼中的XML--------文件读取

时间:2024-03-28 22:36:44

 XML 的初次邂逅

初次邂逅XML

Java眼中的XML--------文件读取

Java眼中的XML--------文件读取

如何进行XML文件解析前的准备工作

在Java程序中如何获取xml文件的内容

在Java程序中读取xml文件的过程也成为----解析xml文件

解析的目的:获取节点名、节点值、属性名、属性值

四种解析方式:DOM  SAX   DOM4J   JDOM

Java眼中的XML--------文件读取

应用 DOM 方式解析 XML

Java眼中的XML--------文件读取

book.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>

DOMTest.java

package com.imooc.domtest.test;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMTest {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // 创建一个DocumentBuilderFactory的对象
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //创建DocumentBuilder的对象
        DocumentBuilder db=dbf.newDocumentBuilder();
        //通过DocumentBuilder对象的parse方法加载books.xml文件到当前项目下
        Document document=db.parse("books.xml");
        //获取所有book节点的集合
        NodeList bookList=document.getElementsByTagName("book");
        //通过NodeList的getLength()方法可以获取bookList的长度
        System.out.println("一共有"+bookList.getLength()+"本书");
        //遍历每个book节点
        for (int i = 0; i < bookList.getLength(); i++) {
            System.out.println("下面开始遍历第"+(i+1)+"本书的内容");
            //通过item(i)方法获取一个book节点,nodeList的索引值0开始
            Node book=bookList.item(i);
            //获取book节点的所有属性集合
            NamedNodeMap attrs=book.getAttributes();
            System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
            //遍历book的属性
            for (int j = 0; j <attrs.getLength(); j++) {
                //通过item(index)方法获取book节点的某一个属性
                Node attr=attrs.item(j);
                //获取属性名
                System.out.println("属性名:"+attr.getNodeName());
                //获取属性值
                System.out.println("属性值:"+attr.getNodeValue());
            }
            //前提:已经知道book节点有且只能有1个id属性
//            //将book节点进行强制类型转换,转换成Element类型
//            Element book = (Element) bookList.item(i);
//            //通过getAttribute("id")方法获取属性值
//            String attrValue = book.getAttribute("id");
//            System.out.println("id属性的属性值为" + attrValue);
            //解析book节点的子节点
            NodeList childNodes=book.getChildNodes();
            //遍历childNodes获取每个节点的节点名和节点值
            System.out.println("第"+(i+1)+"本书共有"+childNodes.getLength()+"个子节点");
            for (int k = 0; k < args.length; k++) {
                //区分出text类型的node以及element类型的node
                if (childNodes.item(k).getNodeType()==Node.ELEMENT_NODE) {
                    //获取了element类型节点的节点名
                    System.out.println("第"+(k+1)+"个节点的节点名:"+childNodes.item(k).getNodeName());
                    //获取了element类型节点的节点值
                    System.out.println("节点值是:"+childNodes.item(k).getFirstChild().getNodeValue());
                }
            }
            System.out.println("===============结束遍历第"+(i+1)+"本书的内容=======================");
        }
    }
}

运行结果为:

Java眼中的XML--------文件读取

应用 SAX 方式解析 XML        

Java眼中的XML--------文件读取                     

  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>

book.java

package com.imooc.entity;

public class Book {
    private String id;
    private String name;
    private String author;
    private String year;
    private String price;
    private String language;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }

}

SAXParserHandler.java

package com.imooc.handler;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.imooc.entity.Book;

public class SAXParserHandler extends DefaultHandler{
    Book book=null;
    String value=null;
    private ArrayList<Book> bookList=new ArrayList<Book>();
    public ArrayList<Book> getBookList(){
        return bookList;

    }
    /*用来标识解析开始*/
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();
        System.out.println("SAX解析开始");
    }

    /*用来标识解析结束*/
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
        System.out.println("SAX解析结束");
    }

    /*开始解析XML元素*/
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //调用DefaultHandler类的startElement方法
        super.startElement(uri, localName, qName, attributes);
        if (qName.equals("book")) {
            //创建一个book对象
            book=new Book();
            //开始解析book元素的属性
            System.out.println("============开始遍历某一本书的内容==============");
            //已知book元素下属性的名称,根据属性名称获取属性值
            value=attributes.getValue("id");
            System.out.println("book的属性值是:"+value);
            //不知道book元素下属的名称以及个数,如何获取属性名以及属性值
            int num=attributes.getLength();
            for (int i = 0; i < num; i++) {
                System.out.println("book元素的第"+(i+1)+"个属性名是"+attributes.getQName(i));
                System.out.println("---属性值是:"+attributes.getValue(i));
                if (attributes.getQName(i).equals("id")) {
                    book.setId(attributes.getValue(i));

                }

            }

        }else if (!qName.equals("name") && !qName.equals("bookstore")) {
            System.out.println("节点名是:"+qName+"----");

        }
    }

    /*结束解析XML元素*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        //调用DefaultHandler类的endElement方法
        super.endElement(uri, localName, qName);
        //判断是否针对一本书已经遍历结束
        if (qName.equals("book")) {
            bookList.add(book);
            book=null;
            System.out.println("==========结束遍历某一本书的内容============");
        }else if (qName.equals("name")) {
            book.setName(value);
        }else if (qName.equals("author")) {
            book.setAuthor(value);
        }else if (qName.equals("year")) {
            book.setYear(value);
        }else if (qName.equals("price")) {
            book.setPrice(value);
        }else if (qName.equals("language")) {
            book.setLanguage(value);
        }
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, length);
        value=new String(ch, start, length);
        if (!value.trim().equals("")) {
            System.out.println("节点值是:"+value);
        }
    }

}

SAXTest.java

package com.imooc.test;

import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXTransformerFactory;

import org.xml.sax.SAXException;

import com.imooc.entity.Book;
import com.imooc.handler.SAXParserHandler;

public class SAXTest {
    public static void main(String[] args) throws Exception {
        // 获取一个SAXTransformerFactory的实例
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // 通过factory获取SAXParser实例
        SAXParser parser = factory.newSAXParser();
        // 创建SAXParserHandler对象
        SAXParserHandler handler = new SAXParserHandler();
        parser.parse("books.xml", handler);
        System.out.println("!~!~共有" + handler.getBookList().size() + "本书");
        for (Book book : handler.getBookList()) {
            System.out.println(book.getId());
            System.out.println(book.getName());
            System.out.println(book.getAuthor());
            System.out.println(book.getYear());
            System.out.println(book.getPrice());
            System.out.println(book.getLanguage());
            System.out.println("--------------finish--------------");
        }

    }
}

运行结果为:

SAX解析开始
============开始遍历某一本书的内容==============
book的属性值是:1
book元素的第1个属性名是id
---属性值是:1
节点值是:冰与火之歌
节点名是:author----
节点值是:乔治马丁
节点名是:year----
节点值是:2014
节点名是:price----
节点值是:89
==========结束遍历某一本书的内容============
============开始遍历某一本书的内容==============
book的属性值是:2
book元素的第1个属性名是id
---属性值是:2
节点值是:安徒生童话
节点名是:year----
节点值是:2004
节点名是:price----
节点值是:77
节点名是:language----
节点值是:English
==========结束遍历某一本书的内容============
SAX解析结束
!~!~共有2本书
1
冰与火之歌
乔治马丁
2014
89
null
--------------finish--------------
2
安徒生童话
null
2004
77
English
--------------finish--------------

 应用DOM4J及JDOM方式解析XML

JDOM

  • JDOM开始解析前的准备工作

第一步:创建java project文件(JDOMTest),创建java包(Package),测试(JDOMTest)

第二部:选择(创建java project文件(JDOMTest))右键——(Buildpath )——(AddExternalArchives)

Java眼中的XML--------文件读取

第三部:选择(src)右键——new ——Folder——创建(res)文件——books.xml

Java眼中的XML--------文件读取

  • JDOM解析

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>

book.java

package com.imooc.entity;

public class Book {
    private String id;
    private String name;
    private String author;
    private String year;
    private String price;
    private String language;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }

}

JDOMTest.java

package com.imooc.jdomtest;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.imooc.entity.Book;

public class JDOMTest {
    private static ArrayList<Book> bookList=new ArrayList<Book>();
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        //进行对books.xml文件的JDOM解析
        //1.创建一个SAXBuilder的对象
        SAXBuilder saxBuilder=new SAXBuilder();
        //2.创建一个输入流,将xml文件加载到输入流中
        InputStream in=new FileInputStream("src/res/books.xml");
        InputStreamReader isr=new InputStreamReader(in, "UTF-8");
        //3.通过SAXBuilder的build方法,将输入流加载到saxBuilder中
        Document document=saxBuilder.build(isr);
        //通过document对象获取xml文件的根节点
        Element rooteElement=document.getRootElement();
        //5.获取根节点下的子节点的booList集合
        List<Element> booList=rooteElement.getChildren();
        //继续进行解析
        for (Element book : booList) {
            Book bookEntity=new Book();
            System.out.println("=====开始解析第"+(bookList.indexOf(book)+1)+"书======");
            //解析book的属性集合
            List<Attribute> attrList=book.getAttributes();
            // //知道节点下属性名称时,获取节点值
            // book.getAttributeValue("id");
            // 遍历attrList(针对不清楚book节点下属性的名字及数量)
            for (Attribute attr : attrList) {
                //获取属性名
                String attrName=attr.getName();
                //获取属性值
                String attrValue=attr.getValue();
                System.out.println("属性名:"+attrName+"----属性值:"+attrValue);
                if (attrName.equals("id")) {
                    bookEntity.setId(attrValue);

                }
            }
            //对book节点的子节点的节点名以及节点值的遍历
            List<Element> bookChilds=book.getChildren();
            for (Element child : bookChilds) {
                System.out.println("节点名:"+child.getName()+"----节点值:"+child.getValue());
                if (child.equals("name")) {
                    bookEntity.setName(child.getValue());
                }else if (child.equals("author")) {
                    bookEntity.setAuthor(child.getValue());
                } else if (child.equals("year")) {
                    bookEntity.setYear(child.getValue());
                }else if (child.equals("price")) {
                    bookEntity.setPrice(child.getValue());
                }else if (child.equals("language")) {
                    bookEntity.setLanguage(child.getValue());
                }
            }
            System.out.println("====结束解析第"+(bookList.indexOf(book)+1)+"书====");
            bookList.add(bookEntity);
            bookEntity=null;
            System.out.println(bookList.size());
            System.out.println(bookList.get(0).getId());
            System.out.println(bookList.get(0).getName());
        }
    }

}

运行结果为:

Java眼中的XML--------文件读取

DOM4J

Java眼中的XML--------文件读取

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>

book.java

package com.imooc.entity;

public class Book {
    private String id;
    private String name;
    private String author;
    private String year;
    private String price;
    private String language;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }

}

DOM4JTest.java

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.Element;
import org.dom4j.io.SAXReader;

import com.imooc.entity.Book;

public class DOM4JTest {
    private static ArrayList<Book> bookList=new ArrayList<Book>();
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // 解析books.xml文件
        //创建SAXReader的对象reader
        SAXReader reader=new SAXReader();
        //通过reader对象的read方法加载books.xml文件,获取document对象
        Document document=reader.read(new File("src/res/books.xml"));
        //通过Element对象获取根节点bookstore
        Element bookStore=document.getRootElement();
        //通过Element对象的elementIterator()方法获取迭代器
        Iterator it=bookStore.elementIterator();
        //遍历迭代器,获取根节点中的信息(书籍)
        while (it.hasNext()) {
            System.out.println("===========开始遍历某一本书===========");
            Element book=(Element) it.next();
            //获取book的属性名以及属性值
            List<Attribute> bookAttrs=book.attributes();
            for (Attribute attr : bookAttrs) {
                System.out.println("属性名:"+attr.getName()+"----属性值:"+attr.getValue());
            }
            Iterator itt=book.elementIterator();
            while (itt.hasNext()) {
                Element bookChild=(Element) itt.next();
                System.out.println("节点名:"+bookChild.getName()+"节点值:"+bookChild.getStringValue());
            }
            System.out.println("===========结束遍历某一本书===========");
        }

    }

}

运行结果为:

Java眼中的XML--------文件读取

 四种XML解析方式大PK

  • 四种解析方式的 分析
  1. 1.DOM4J
  2. SAX
  3. JDOM
  4. DOM

Java眼中的XML--------文件读取

Java眼中的XML--------文件读取

选择DOM还是SAX???

DOM

——优点:

  • 形成了树结构,直观好理解,代码更容易编写
  • 解析过程中结构保留在内存中,方便修改

——缺点:

  • 当xml文件较大时,对内存耗费比较大,容易影响解析性能并造成内存溢出

SAX

——优点:

  • 采用事件驱动模式,对内存耗费比较小
  • 使用于只需要处理xml中数据时

——缺点:

  • 不易编码
  • 很难同时访问同一个xml中的多处不同数据

JDOM与DOM、DOM4J

JDOM

  • 仅使用具体类而不使用接口
  • API大量使用了Collections类

JDOM 4J

  • JDOM 的一种智能分支,它合并了许多超出基本XML文档表示的功能
  • DOM4J使用接口和抽象基本类方法,是一个优秀的Java XML API
  • 具有性能优异、灵活性好、功能强大和极端易用使用的特点
  • 是一个开源代码的软件
  •  四种解析方式解析速度分析

Java眼中的XML--------文件读取

JUnit4创建布局:

Java眼中的XML--------文件读取

Book.java

package com.imooc.entity;

public class Book {
    private String id;
    private String name;
    private String author;
    private String year;
    private String price;
    private String language;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }

}

SAXParseHandler.java

package com.imooc.handler;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.imooc.entity.Book;

public class SAXParseHandler extends DefaultHandler{
    String value=null;
    Book book=null;
    private ArrayList<Book> booklList=new ArrayList<Book>();
    public ArrayList<Book> getBooklList() {
        return booklList;
    }

    /*用来标识解析开始*/
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();
    }

/*用来标识解析结束*/
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
    }

    /*解析XML元素*/
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // TODO Auto-generated method stub
        super.startElement(uri, localName, qName, attributes);
        if (qName.equals("book")) {
            book=new Book();
            value=attributes.getValue("id");
            int num=attributes.getLength();
            for (int i = 0; i < num; i++) {
                if (attributes.getQName(i).equals("id")) {
                    book.setId(attributes.getValue(i));
                }
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        super.endElement(uri, localName, qName);
        if (qName.equals("book")) {
            booklList.add(book);
            book=null;
        }else if (qName.equals("name")) {
            book.setName(value);
        }else if (qName.equals("name")) {
            book.setAuthor(value);
        }else if (qName.equals("name")) {
            book.setYear(value);
        }else if (qName.equals("name")) {
            book.setPrice(value);
        }else if (qName.equals(value)) {
            book.setLanguage(value);
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        super.characters(ch, start, length);
        String temp=new String(ch, start, length);
        if (!temp.trim().equals("")) {
            value=temp;
        }
    }

}

ParseTest.java

package com.parser.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.dom4j.io.SAXReader;
import org.jdom2.Attribute;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.imooc.entity.Book;
import com.imooc.handler.SAXParseHandler;

public class ParseTest{
    //DOM
    public void domXmlParser() throws Exception{
        ArrayList<Book> bookLists=new ArrayList<Book>();
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder db=dbf.newDocumentBuilder();
        Document document=db.parse("books.xml");
        NodeList bookList=document.getElementsByTagName("book");
        for (int i = 0; i < bookList.getLength(); i++) {
            Node book=bookList.item(i);
            Book bookEntity=new Book();
            NamedNodeMap attrs=book.getAttributes();
            for (int j = 0; j < attrs.getLength(); j++) {
                Node attr=attrs.item(j);
                if (attr.getNodeName().equals("id")) {
                    bookEntity.setId(attr.getNodeValue());
                }
            }
            NodeList childNodes=book.getChildNodes();
            for (int k = 0; k < childNodes.getLength(); k++) {
                if (childNodes.item(k).getNodeType()==Node.ELEMENT_NODE) {
                    String name=childNodes.item(k).getNodeName();
                    String value=childNodes.item(k).getNodeValue();
                    if (name.equals("name")) {
                        bookEntity.setName(value);
                    }else if (name.equals("author")) {
                        bookEntity.setAuthor(value);
                    }else if (name.equals("year")) {
                        bookEntity.setYear(value);
                    }else if (name.equals("price")) {
                        bookEntity.setPrice(value);
                    }else if (name.equals("language")) {
                        bookEntity.setLanguage(value);
                    }
                }
            }
            bookLists.add(bookEntity);
            bookEntity=null;

        }    

    }

    //SAX
    public void saxXmlParser() throws Exception{
        SAXParserFactory factory=SAXParserFactory.newInstance();
        SAXParser parser=factory.newSAXParser();
        SAXParseHandler handler=new SAXParseHandler();
        parser.parse("books.xml", handler);
    }

    //JDOM
    public void jdomXmlParser() throws Exception{
        ArrayList<Book> booksList=new ArrayList<Book>();
        SAXBuilder saxBuilder=new SAXBuilder();
        InputStream in=new FileInputStream("books.xml");
        InputStreamReader isr=new InputStreamReader(in,"UTF-8");
        org.jdom2.Document document=saxBuilder.build(isr);
        org.jdom2.Element rooteElement=document.getRootElement();
        List<org.jdom2.Element> bookList=rooteElement.getChildren();
        for (Element book : bookList) {
            Book bookEntity=new Book();
            List<Attribute> attrList=book.getAttributes();
            for (Attribute attr : attrList) {
                String attrName=attr.getName();
                String attrValue=attr.getValue();
                if (attrName.equals("id")) {
                    bookEntity.setId(attrValue);
                }
            }
            List<org.jdom2.Element> bookChilds=book.getChildren();
            for (org.jdom2.Element child : bookChilds) {
                if (child.getName().equals("name")) {
                    bookEntity.setName(child.getValue());
                }else if (child.getName().equals("author")) {
                    bookEntity.setAuthor(child.getValue());
                }else if (child.getName().equals("year")) {
                    bookEntity.setYear(child.getValue());
                }else if (child.getName().equals("price")) {
                    bookEntity.setPrice(child.getValue());
                }else if (child.getName().equals("language")) {
                    bookEntity.setLanguage(child.getValue());
                }
            }
            booksList.add(bookEntity);
            bookEntity=null;
        }
    }

    //DOM4J
    public void dom4jXmlParser() throws Exception{
        ArrayList<Book> booksListss=new ArrayList<Book>();
        SAXReader reader=new SAXReader();
        org.dom4j.Document document=reader.read(new File("books.xml"));
        org.dom4j.Element bookStore=document.getRootElement();
        List<org.dom4j.Element> bookEles=bookStore.elements();
        for (org.dom4j.Element book : bookEles) {
            Book bookEntity=new Book();
            List<org.dom4j.Attribute> bookAttrs=book.attributes();
            for (org.dom4j.Attribute attr : bookAttrs) {
                if (attr.getName().equals("id")) {
                    bookEntity.setId(attr.getValue());
                }
            }
            List<org.dom4j.Element> bookss=book.elements();
            for (org.dom4j.Element bookChild : bookss) {
                String name=bookChild.getName();
                String value=bookChild.getStringValue();
                if (name.equals("name")) {
                    bookEntity.setName(value);
                }else if (name.equals("author")) {
                    bookEntity.setAuthor(value);
                }else if (name.equals("year")) {
                    bookEntity.setYear(value);
                }else if (name.equals("price")) {
                    bookEntity.setPrice(value);
                }else if (name.equals("language")) {
                    bookEntity.setLanguage(value);
                }
            }
            booksListss.add(bookEntity);
            bookEntity=null;
        }
    }

    @Test
    public void testPerformance() throws Exception{
        System.out.println("性能测试:");
        //测试DOM的性能
        long start=System.currentTimeMillis();
        domXmlParser();
        System.out.println("DOM:"+(System.currentTimeMillis()-start));

        //测试SAX的性能
        start=System.currentTimeMillis();
        saxXmlParser();
        System.out.println("SAX:"+(System.currentTimeMillis()-start));

        //测试JDOM的性能
        start=System.currentTimeMillis();
        jdomXmlParser();
        System.out.println("JDOM:"+(System.currentTimeMillis()-start));

        //测试DOM4J
        start=System.currentTimeMillis();
        dom4jXmlParser();
        System.out.println("DOM4J:"+(System.currentTimeMillis()-start));
    }

}

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>

测试结果为:

Java眼中的XML--------文件读取