SAX解析XML

Book.xml源文件

<?xml version="1.0" encoding="UTF-8"?>
<BOOKS:BOOKS>
    <BOOK ID="1001">
        <NAME>三国演义</NAME>
        <PRICE>15</PRICE>
    </BOOK>
    <BOOK ID="1002">
        <NAME>水浒传</NAME>
        <PRICE>14</PRICE>
    </BOOK>
</BOOKS:BOOKS>

下面开始解析XML

//SAX解析工厂
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
//工厂创建解析器
SAXParser saxParser = saxParserFactory.newSAXParser();
//解析器获取读取器
XMLReader xmlReader = saxParser.getXMLReader();
//在读取器中注册监听
MyContentHandler mch = new MyContentHandler();
xmlReader.setContentHandler(mch); 
//读取器开始解析
xmlReader.parse("Book.xml");

实现解析监听接口ContentHandler

//自定义内部类,实现监听接口
class MyContentHandler implements ContentHandler{
    @Override
    public void startDocument() throws SAXException {
        System.out.println("文档开始");
    }

    @Override
    public void endDocument() throws SAXException {
        System.out.println("文档结束");
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {
        //uri:名称空间 URI,如果没有为""空串
        //localName:标签名称,不带前缀(如果没有执行名称空间处理,为""空串)
        //qName:标签名称:带有前缀
        //atts:属性
        System.out.println("标签的开始");
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        System.out.println("标签的结束");
    }

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

    @Override
    public void setDocumentLocator(Locator locator) {
    }

    @Override
    public void startPrefixMapping(String prefix, String uri)
            throws SAXException {

    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {

    }

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length)
            throws SAXException {
    }

    @Override
    public void processingInstruction(String target, String data)
            throws SAXException {
    }

    @Override
    public void skippedEntity(String name) throws SAXException {
    }


}

你可能感兴趣的:(java,android,xml,sax,解析xml)