用JAXP的SAX方式解析XML文件

简单用JAXP的SAX方式(事件驱动)解析XML文件:

文件(1.XML)

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<class>
    <student>
        <name>张三</name>
        <sid>111111</sid>
    </student>
    <student>
        <name>李四</name>
        <sid>222222</sid>
    </student>
</class>

 Java代码

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 JaxpSax {
    public static void main(String[] args) throws Exception {
        SAXParserFactory factory=SAXParserFactory.newInstance();
        SAXParser parser=factory.newSAXParser();
        parser.parse("src/1.xml", new MyHandler1());//在控制台打印出XML文件
        //parser.parse("src/1.xml", new MyHandler2());//在控制台打印所有学生姓名
    }
}
class MyHandler1 extends DefaultHandler{
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.print("<"+qName+">");
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        System.out.print(new String(ch,start,length));
    }
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        System.out.print("</"+qName+">");
    }
}
class MyHandler2 extends DefaultHandler{

    boolean flag=true;
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if(qName.equals("name")) flag=true;
    }
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if(flag) System.out.println(new String(ch,start,length));
    }
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if(qName.equals("name")) flag=false;
    }
}

 控制台运行结果:

posted @ 2016-10-13 21:10  凌晨。。。三点  阅读(278)  评论(0编辑  收藏  举报