SAX - Hello World

SAX 是一种事件驱动的 XML 数据处理模型。对于 DOM 模型,解析 XML 文档时,需要将所有内容载入内容。相比 DOM 模型,SAX 模型更为高效,它一边扫描一边解析 XML 文档。但与 DOM 模型相比,SAX 的操作更为复杂。

 

简单示例:

package com.huey.hello.sax;

import java.io.InputStream;
import java.io.StringWriter;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class MySAXApp extends DefaultHandler {
    
    private StringWriter writer;

    public MySAXApp() {
        super();
    }

    public static void main(String args[]) throws Exception {
        XMLReader xr = XMLReaderFactory.createXMLReader();
        MySAXApp handler = new MySAXApp();
        xr.setContentHandler(handler);
        xr.setErrorHandler(handler);
        
        InputStream inStream = MySAXApp.class.getResourceAsStream("/files/hello.xml");
        InputSource inSource = new InputSource(inStream);
        xr.parse(inSource);
    }
    
    @Override
    public void startDocument() throws SAXException {
        writer = new StringWriter();
    }
    
    @Override
    public void endDocument() throws SAXException {
        System.out.println(writer.toString());
    }
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {        
        writer.append('<').append(qName);
        for (int i = 0; i < attributes.getLength(); i++) {
            writer.append(' ')
                .append(attributes.getLocalName(i))
                .append('=').append('"')
                .append(attributes.getValue(i))
                .append('"');
        }
        writer.append('>');
    }    
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {        
        writer.append("</").append(qName).append('>');        
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        String text = new String(ch, start, length);
        writer.append(text);
    }
}

 

posted on 2016-05-21 17:12  huey2672  阅读(261)  评论(0编辑  收藏  举报