天天看點

DOM、SAX、JDOM、DOM4J四種方式解析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>           

1.DOM方式解析,官方提供,一次加載xml檔案到記憶體中,對于xml檔案過大的支援效率不好

public static void main(String[] args) {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse("books.xml");
            NodeList books = document.getElementsByTagName("book");
            for(int i = 0;i<books.getLength();i++){
                System.out.println("開始周遊第"+(i+1)+"本書");
                Element book = (Element) books.item(i);
                String id = book.getAttribute("id");
                System.out.println("id:"+id);
                NodeList nodeList = books.item(i).getChildNodes();
                for(int j = 0;j<nodeList.getLength();j++){
                    if(nodeList.item(j).getNodeType()==Node.ELEMENT_NODE){
                        System.out.println(nodeList.item(j).getNodeName()+":"+nodeList.item(j).getTextContent());
                    }
                }
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }           

2.SAX方式解析,官方提供,逐個讀取xml檔案得節點,對xml檔案較大的,支援良好,使用需繼承DefaultHandler接口

package com.example.xml;

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

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

public class SAXParserHandler extends DefaultHandler {
    Book book = null;
    String value = null;
    List<Book> books = new ArrayList<>();

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if(qName.equals("book")){
            book = new Book();
            for(int i =0;i<attributes.getLength();i++){
                if(attributes.getQName(i).equals("id")){
                    book.setId(attributes.getValue(i));
                }
                System.out.println(attributes.getQName(i)+":"+attributes.getValue(i));
            }
        }else if(!qName.equals("bookstore")){
            System.out.print(qName+":");
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        if(qName.equals("book")){
            books.add(book);
            book = null;
        }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 startDocument() throws SAXException {
        super.startDocument();
        System.out.println("SAX解析開始");
    }

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

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        value = new String(ch,start,length);
        if(!value.trim().equals("")){
            System.out.println(value);
        }
    }

    public List<Book> getBooks() {
        return books;
    }
}           
@Test
    public  void Sax() throws IOException, ParserConfigurationException, SAXException {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxParserFactory.newSAXParser();
        SAXParserHandler saxParserHandler = new SAXParserHandler();
        saxParser.parse("books.xml", saxParserHandler);
        List<Book> books = saxParserHandler.getBooks();
        for(Book book:books){
            System.out.println(book);
        }
    }           

3.JDOM解析,第三方提供

package com.example.xml;

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

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

public class JDOMTest {

    public static void main(String[] args) throws IOException, JDOMException {
        SAXBuilder saxBuilder = new SAXBuilder();
        FileInputStream fileInputStream = new FileInputStream(new File("books.xml"));
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"utf-8");
        Document document = saxBuilder.build(inputStreamReader);
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.getChildren();
        List<Book> bookEntites = new ArrayList<>();
        for(Element element:elements){
            Book bookEntity = new Book();
            List<Attribute> attributes = element.getAttributes();
            for(Attribute attr:attributes){
                if(attr.getName().equals("id")){
                    bookEntity.setId(attr.getValue());
                }
                System.out.println(attr.getName()+"-----------"+attr.getValue());
            }
            List<Element> books = element.getChildren();
            for(Element book:books){
                String name = book.getName();
                String value = book.getValue();
                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);
                }
                System.out.println(name+"--------"+value);
            }
            bookEntites.add(bookEntity);
        }

        System.out.println("====================================================================");
        for(Book book:bookEntites){
            System.out.println(book);
        }

    }
}
           

4.DOM4J解析,第三方提供,使用比較簡單,效率也比較好,應用比較廣泛

package com.example.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.util.Iterator;
import java.util.List;

public class DOM4JTest {

    public static void main(String[] args) throws DocumentException, FileNotFoundException, UnsupportedEncodingException {

        SAXReader saxReader = new SAXReader();
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("books.xml"),"utf-8");
        Document document = saxReader.read(inputStreamReader);
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element element = (Element) iterator.next();
            List<Attribute> attributes = element.attributes();
            for(Attribute attr:attributes){
                System.out.println(attr.getName()+"---------------"+attr.getValue());
            }
            List<Element> books = element.elements();
            for (Element element1:books){
                System.out.println(element1.getName()+"---------------"+element1.getStringValue());
            }
        }

    }
}           
下一篇: 支付寶