zno2

event based xml parser (SAX) demo

 

import java.io.ByteArrayInputStream;

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 Test {
    public static void main(String[] args) throws Exception {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        String s = "<班级 id=\"1\"><教师 id=\"2\">王老师</教师><学生 id=\"3\">小明</学生></班级>";
        ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes("utf-8"));
        SaxHandler handler = new SaxHandler();
        parser.parse(is, handler);
    }
}

class SaxHandler extends DefaultHandler {
    @Override
    public void startDocument() throws SAXException {
        System.out.println("start document");
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.println(uri + "|" + localName + "|" + qName + "|" + attributes.getValue(0));
    }

    @Override
    public void characters(char ch[], int start, int length) throws SAXException {
        System.out.println(new String(ch, start, length));
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.println(uri + "!" + localName + "!" + qName);
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("end document");
    }
}

 

运行结果:

start document
||班级|1
||教师|2
王老师
!!教师
||学生|3
小明
!!学生
!!班级
end document

 

posted on 2017-10-19 10:01  zno2  阅读(132)  评论(0编辑  收藏  举报

导航