JAXP之SAX解析

package cn.itcast.jaxp.sax;
import java.io.IOException;
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;
/**
 * XML解析之SAX
 * @author Lynch
 *
 */
public class SAXTest {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        retrieve();
    }
      
    /**
     * 查询节点
     * @throws SAXException
     * @throws ParserConfigurationException
     * @throws IOException
     */
    public static void retrieve() throws ParserConfigurationException, SAXException, IOException {
        // 创建解析器工厂
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        // 创建解析器
        SAXParser saxParser = saxParserFactory.newSAXParser();
        // 解析文档,同时绑定Handler
        saxParser.parse("src/book.xml", new MyDefaultHandler());
    }
}
class MyDefaultHandler extends DefaultHandler {
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        System.out.print("<" + qName + ">");
    }
    @Override
    public void endElement(String uri, String localName, String qName)
            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));
    }
      
}


本文出自 “狐灵传说” 博客,转载请与作者联系!

你可能感兴趣的:(import,public)