1. 程式人生 > >使用SAX方式解析XML

使用SAX方式解析XML

一、建立XML檔案
這裡寫圖片描述

目錄結構:
這裡寫圖片描述

二、新建一個帶有main方法的類(SAXTest.java)

public class SAXTest {
    public static void main(String[] args) {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            SAXParserHandle handle = new
SAXParserHandle(); parser.parse("books.xml", handle); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch
(IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

三、新建Handle類,繼承DefaultHandler

public class SAXParserHandle extends DefaultHandler {
    /*
     * 標識解析開始
     * @see org.xml.sax.helpers.DefaultHandler#startDocument()
     */
    @Override
public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); System.out.println("----解析開始----"); } /* * 標識解析結束 * @see org.xml.sax.helpers.DefaultHandler#endDocument() */ @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); System.out.println("----解析結束----"); } /* * 解析XML元素 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String arg0, String arg1, String name, Attributes attributes) throws SAXException { // TODO Auto-generated method stub super.startElement(arg0, arg1, name, attributes); if(name.equals("book")){ System.out.println("==========開始遍歷某一本書的內容=========="); int length = attributes.getLength(); for(int i=0;i<length;i++){ System.out.print("屬性:"+attributes.getQName(i)); System.out.println("---值:"+attributes.getValue(i)); } }else if(!name.equals("book") && !name.equals("bookstore")){ System.out.print("節點:"+ name); } } @Override public void endElement(String arg0, String arg1, String name) throws SAXException { // TODO Auto-generated method stub super.endElement(arg0, arg1, name); if(name.equals("book")){ System.out.println("==========結束遍歷某一本書的內容=========="); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); String nodeValue = new String(ch, start, length); if(!nodeValue.trim().equals("")){ System.out.println("值:"+nodeValue); } } }

解析結果:
這裡寫圖片描述