天天看點

xml解析---java的DOM,SAX,JDOM,DOM4J

xml是一種常見的文本格式,可以為我們提供各系統件資訊傳輸的标準,以及資訊持久化存儲的模式。通常在接口設計上,封包格式往往就是json和xml兩種。json來說更輕量一點,解析也相對容易。

然而現在是xml的時間。。。

java中解析xml方式常見有4種

官方提供的兩種

1. DOM

2. SAX

擴充方式2種

1. JDOM

2. DOM4J

DOM是 W3C 組織推薦的處理 XML 的一種方式,JDOM和DOM4J這兩種和DOM屬于同一種模式都是把xml檔案一次讀入記憶體,将其作為一個樹這種層次來解析。因為一次性讀入記憶體,導緻大檔案讀取性能上會弱一點。

SAX與DOM方法不同,是一種基于事件的讀取模式。讀到相應的節點,觸發相應的事件。不需要像DOM一樣,一開始讀入記憶體中。性能上會優勢些。但是這種事件模式上,在檔案内容比較複雜的xml檔案讀取上就會顯得比較麻煩。各個節點互相的關系,不容易關聯,操作上會沒有DOM方法靈活,代碼可讀性會很糟糕。

JDOM使用上相對簡單點,提供一些collection的集合架構,但是性能上比DOM方式弱一點。重在簡單。

DOM4J在性能上優于DOM和JDOM, DOM是XML的标準基礎,DOM4J性能上又最好(除了SAX),JDOM的話使用上會更友善一點(其實我覺得都差不多),但是性能最弱。SAX這種在xml檔案複雜的情況下程式設計模式上會沒有DOM這些便利。

下面代碼記錄,代碼上都比較簡單,都是簡單讀取節點,擷取節點屬性,以及子節點中的值資訊。

xml檔案 Books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1">
        <name>think in java</name>
        <author>tom</author>
        <date>2018</date>
    </book>
    <book id ="2" att="hhh">
        <name>html design</name>
        <author>jack</author>
        <price>100</price>
    </book>
</books>           

實體類

package com.yangs.xml.bean;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class Book {
    private String id;
    private String att;

    private String name;
    private String author;
    private String date;
    private String price;

   getter()...
   setter()...

    @Override
    public String toString() {
        return "Book{" +
                "id='" + id + '\'' +
                ", att='" + att + '\'' +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", date='" + date + '\'' +
                ", price='" + price + '\'' +
                '}';
    }
}           

DOM

package com.yangs.xml.dom;

import com.yangs.xml.bean.Book;
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 javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class DOMTest2 {
    public static void main(String[] args) {
        List<Book> list = new ArrayList<>();

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse("src/com/yangs/xml/Books.xml");

            NodeList books = document.getElementsByTagName("book");
            for(int i = 0; i < books.getLength(); i++){
                //某個書
                Book book = new Book();
                list.add(book);

                Node itemBook = books.item(i);
                //屬性
                NamedNodeMap attrs = itemBook.getAttributes();
                for(int j = 0; j < attrs.getLength(); j++){
                    //某個屬性
                    Node attr = attrs.item(j);
                    if("id".equals(attr.getNodeName())){
                        book.setId(attr.getNodeValue());
                    }else if("att".equals(attr.getNodeName())){
                        book.setAtt(attr.getNodeValue());
                    }
                }

                //子節點
                NodeList children = itemBook.getChildNodes();
                for(int j = 0; j < children.getLength(); j++){
                    //某個節點
                    Node child = children.item(j);
                    if(child.getNodeType() == Node.ELEMENT_NODE) {//過濾空格,換行這些人為添加的 有助于展示檢視的東西
                        if ("name".equals(child.getNodeName())){
                            book.setName(child.getTextContent());
                        }else if ("author".equals(child.getNodeName())){
                            book.setAuthor(child.getTextContent());
                        }else if ("price".equals(child.getNodeName())){
                            book.setPrice(child.getTextContent());
                        }else if ("date".equals(child.getNodeName())){
                            book.setDate(child.getTextContent());
                        }
                    }
                }
            }

            //展示
            for(Book b : list){
                System.out.println(b.toString());
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}           

SAX

處理事件類

package com.yangs.xml.sax;

import com.sun.org.apache.xml.internal.resolver.readers.SAXParserHandler;
import com.yangs.xml.bean.Book;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class MySAXHandler extends SAXParserHandler{
    //private int bookIndex;//指向第幾本書
    private Book book;
    private List<Book> list = new ArrayList<>();

    private String tmpVlaue;//用于記錄book每一個屬性的值

    public List<Book> getList() {
        return list;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        tmpVlaue = new String(ch, start, length);

    }

    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
        super.endElement(namespaceURI, localName, qName);
        if("book".equals(qName)){
            book = null;//一次book資訊周遊完成嗎,清緩存
        }
        //設定參數
        else if("name".equals(qName)){
            book.setName(tmpVlaue);
        }else if("author".equals(qName)){
            book.setAuthor(tmpVlaue);
        }else if("date".equals(qName)){
            book.setDate(tmpVlaue);
        }else if("price".equals(qName)){
            book.setPrice(tmpVlaue);
        }else{
            //System.out.println("bad");
        }
    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        super.startElement(namespaceURI, localName, qName, atts);
        if("book".equals(qName)){
            //bookIndex++;
            //添加新書
            book = new Book();
            list.add(book);

            //book标簽上的屬性
            for(int i =0; i < atts.getLength(); i++){
                String attrName = atts.getQName(i);
                if("id".equals(attrName)){
                    book.setId(atts.getValue(i));
                }else if("att".equals(attrName)){
                    book.setAtt(atts.getValue(i));
                }else{
                    System.out.println("非法的屬性"+ atts.getQName(i));
                }
            }
        }
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("解析開始-----");
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("解析結束-----");
    }
}           

主邏輯

package com.yangs.xml.sax;

import com.yangs.xml.bean.Book;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.util.List;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class SAXTest {
    public static void main(String[] args) {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = saxParserFactory.newSAXParser();
            MySAXHandler handler = new MySAXHandler();
            saxParser.parse("src/com/yangs/xml/Books.xml", handler);
            List<Book> list = handler.getList();
            for(Book book : list){
                System.out.println(book.toString());
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}           

JDOM

package com.yangs.xml.jdom;

import com.yangs.xml.bean.Book;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class JDOMTest {
    public static void main(String[] args) {
        List<Book> list = new ArrayList<>();//存儲查詢到的對象

        try {
            InputStream inputStream = new FileInputStream("src/com/yangs/xml/Books.xml");
            SAXBuilder saxBuilder = new SAXBuilder();
            Document document = saxBuilder.build(inputStream);
            Element root = document.getRootElement();
            List<Element> books = root.getChildren("book");
            for(Element b : books){
                //新book
                Book book = new Book();
                list.add(book);

                //屬性
                List<Attribute> attributes = b.getAttributes();
                for(Attribute a : attributes){
                    if("id".equals(a.getName())){
                        book.setId(a.getValue());
                    }else if("att".equals(a.getValue())){
                        book.setAtt(a.getValue());
                    }
                }

                //子節點
                List<Element> elements = b.getChildren();
                for(Element e : elements){
                    if("name".equals(e.getName())) {
                        book.setName(e.getValue());
                    }else if("author".equals(e.getName())) {
                        book.setAuthor(e.getValue());
                    }else if("date".equals(e.getName())) {
                        book.setDate(e.getValue());
                    }else if("price".equals(e.getName())) {
                        book.setPrice(e.getValue());
                    }
                }

            }

            //輸出結果
            for(Book b : list){
                System.out.println(b.toString());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}           

DOM4J

package com.yangs.xml.dom4j;

import com.yangs.xml.bean.Book;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Ytadpole on 2018/2/19.
 */
public class DOM4JTest {
    public static void main(String[] args) {
        List<Book> list = new ArrayList<>();

        SAXReader saxReader = new SAXReader();
        try {
            //加載檔案
            Document document = saxReader.read(new File("src/com/yangs/xml/Books.xml"));
            //root節點
            Element root = (Element) document.getRootElement();
            Iterator books = root.elementIterator();
            while (books.hasNext()){
                //新書
                Book book = new Book();
                list.add(book);
                Element b = (Element) books.next();

                //屬性
                Iterator<Attribute> attrs = b.attributeIterator();
                while(attrs.hasNext()){
                    //某個屬性
                    Attribute attr = attrs.next();
                    if("id".equals(attr.getName())){
                        book.setId(attr.getValue());
                    }else if("att".equals(attr.getName())){
                        book.setAtt(attr.getValue());
                    }
                }

                //子節點
                Iterator children = b.elementIterator();
                while(children.hasNext()){
                    //某個子節點
                    Element child = (Element) children.next();
                    if("name".equals(child.getName())){
                        book.setName(child.getStringValue());
                    }else if("author".equals(child.getName())){
                        book.setAuthor(child.getStringValue());
                    }else if("date".equals(child.getName())){
                        book.setDate(child.getStringValue());
                    }else if("price".equals(child.getName())){
                        book.setPrice(child.getStringValue());
                    }
                }
            }

            //展示
            for(Book b : list){
                System.out.println(b.toString());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}