Java xml解析(DOM、SAX)

test.mxl

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="12">
        <name>thinking in java</name>
        <price>85.5</price>
    </book>
    <book id="15">
        <name>Spring in Action</name>
        <price>39.0</price>
    </book>
</books>

封装成一个对象

package com.hz;
/**
 * 封装book对象
 * 
 * @author ztw
 *
 * 2016-12-20
 */
public class Book {

    private String id;
    private String name;
    private double price;
    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 double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(price) != Double
                .doubleToLongBits(other.price))
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", price=" + price + "]\n";
    }

}
三步曲走起:

1、创建解析器工厂
2、新建解析器
3、使用解析器解析文档,获取文档对象

DOM解析

tree

package com.hz.dom;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.hz.Book;

/**
 * DOM解析
 * 
 * @author ztw
 *
 * 2016-12-20
 */
public class DOMParse {

    public static List<Book> Parse(String fileName){
        List<Book> result = new  ArrayList<Book>();
        //1、创建解析器工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            //2、新建解析器
            DocumentBuilder builder = dbf.newDocumentBuilder();
            //3、使用解析器解析文档,获取文档对象
            Document document = builder.parse(fileName);
            //目标是解析book对象

            //包含node的容器List<Book>
            NodeList nodeList = document.getElementsByTagName("book");
            //获取到的长度
            int count = nodeList.getLength();

            for (int i = 0; i < count; i++) {
                Book book = new Book();
                //获取到nodeList中的每一个node节点
                //强制转换成元素节点
                Element elementsNode = (Element) nodeList.item(i);
                //获取id属性
                String id = elementsNode.getAttribute("id");
                book.setId(id);
                //获取当前elementsNode的子节点
                NodeList childNodesList = elementsNode.getChildNodes();

                int size = childNodesList.getLength();

                for (int j = 0; j < size; j++) {
                    //这里的node有两种节点  文本节点   元素节点
                    Node childNode = childNodesList.item(j);

                    if(childNode.getNodeType() == Node.ELEMENT_NODE){

                        Element childElementsNode = (Element) childNode;

                        if("name".equals(childElementsNode.getTagName())){
                            String name = childElementsNode.getFirstChild().getNodeValue();
                            book.setName(name);

                        }else if("price".equals(childElementsNode.getTagName())){
                            String priceStr = childElementsNode.getFirstChild().getNodeValue();
                            try {
                                book.setPrice(Double.valueOf(priceStr));
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                result.add(book);
            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

SAX解析

逐行解析

package com.hz.sax;

import java.io.File;
import java.io.IOException;

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

import org.xml.sax.SAXException;
/**
 * SAX解析
 * 
 * @author ztw
 *
 * 2016-12-20
 */
public class SaxParse {

    public static void parse(String fileName){

        //1 创建解析工厂
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {
            //创建解析器
            SAXParser parse = spf.newSAXParser();

            parse.parse(new File(fileName), new MyDefaultHandler());

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package com.hz.sax;

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

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

import com.hz.Book;
/**
 * 重写DefaultHandler中的方法
 * 
 * @author ztw
 *
 * 2016-12-20
 */
public class MyDefaultHandler extends DefaultHandler {

    private List<Book> bookList;

    private Book book;

    private String tag;
    /**
     * 在文档解析开始之前调用
     */
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        bookList = new ArrayList<Book>();
    }

    /**
     * 标签的开始
     */
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        tag = qName;
        if("book".equals(qName)){
            book = new Book();
            String id = attributes.getValue("id");
            book.setId(id);
        }
    }

    /**
     * 对文本的解析
     */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);

        String str = new String(ch, start, length);

        if(tag.equals("name")){
            book.setName(str);

        }else if(tag.equals("price")){
            try {
                book.setPrice(Double.valueOf(str));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 标签的结束
     */
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(uri, localName, qName);
        if(qName.equals("book")){
            bookList.add(book);
        }
        tag = "";
    }


    /**
     * 在文档解析结束之后调用
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println(bookList);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值