`
w0rchid
  • 浏览: 11653 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

SAX解析xml(自用)

 
阅读更多
package com.huawei.t0906_SAX;

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

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

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


public class SaxParserXml extends DefaultHandler
{
    // xml文件的路径
    private static final String PATH = "test_book.xml";  
   
    private List<Book> books = null;
   
    private Book book;
   
    // 用来记录解析时上一个节点的名称
    private String preTag = null;
  
    public static List<Book> getBooks(InputStream is) throws ParserConfigurationException, SAXException, IOException
    {
        SAXParserFactory sf = SAXParserFactory.newInstance();
        SAXParser sp = sf.newSAXParser();
       
        SaxParserXml spx = new SaxParserXml();
        sp.parse(is, spx);
       
        return spx.getBooks();
    }

    private List<Book> getBooks()
    {
        return books;
    }
   
    @Override
    public void startDocument() throws SAXException
    {
        books = new ArrayList<Book>();
    }
   
    @Override
    public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException
    {
        if ("book".equals(qName))
        {
            book = new Book();
            book.setId(attributes.getValue(0));
        }
       
        // 将正在解析的节点赋给preTag
        preTag = qName;
    }
   
    @Override
    public void endElement(String uri, String localName, String qName)
        throws SAXException
    {
        if ("book".equals(qName))
        {
            books.add(book);
            book = null;
        }
        preTag = null;
    }
   
    @Override
    public void characters(char[] ch, int start, int length)
        throws SAXException
    {
        String content = new String(ch, start, length);
        if ("name".equals(preTag))
        {
            book.setName(content);
        }
        else if ("price".equals(preTag))
        {
            book.setPrice(Double.valueOf(content));
        }
    }
   
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
    {
        InputStream is = new SaxParserXml().getClass().getClassLoader().getResourceAsStream(PATH);
       
        List<Book> books = getBooks(is);
       
        for (Book b : books)
        {
            System.out.println(b);
        }
    }
   
   
}
------------------------DOM----------------------------
package com.huawei.t0906_DOM2;

import java.io.IOException;
import java.io.InputStream;
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;

public class DomPaseXml_Element
{
    // xml文件路径
    private static final String PATH = "test_book.xml";
    /**
     *  dom 解析xml
     *
     * @param input
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException [参数说明]
     *
     * @return List<Book> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static List<Book> getBooks(InputStream input) throws ParserConfigurationException, SAXException, IOException
    {
        List<Book> books = new ArrayList<Book>();
        DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = df.newDocumentBuilder();
        Document document = db.parse(input);
        Element element = document.getDocumentElement();
       
        // 获得book
        NodeList bookNodes = element.getElementsByTagName("book");
       
        // book集合的长度
        int length1 = bookNodes.getLength();
       
        for (int i = 0; i < length1; i++)
        {
            Element bookElememt = (Element)bookNodes.item(i);
            Book book = new Book();
            // 设置图书id
            book.setId(bookElememt.getAttribute("id"));
           
            NodeList childNodes = bookElememt.getChildNodes();
           
            // book元素下的长度
            int length2 = childNodes.getLength();
           
            for (int j = 0; j < length2; j++)
            {
                if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE)
                {
                    if ("name".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setName(childNodes.item(j).getFirstChild().getNodeValue());
                    }
                    else if ("price".equals(childNodes.item(j).getNodeName()))
                    {
                        book.setPrice(Double.valueOf(childNodes.item(j).getFirstChild().getNodeValue()));
                    }
                } // end of - if()
            } // end of - for(j)
           
            // 添加图书
            books.add(book);
        } // end of for(i)
       
        return books;
    }
   
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException
    {
        // 构建xml文件的数据流
        InputStream is = new DomPaseXml_Element().getClass().getClassLoader().getResourceAsStream(PATH);
       
        // 解析xml获得实力数据
        List<Book> list = getBooks(is);
       
        for (Book b : list)
        {
            System.out.println(b.getId() + "-" + b);
        }
       
    }
   
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics