解析XML文件——SAX基本操作

1.SAX的主要事件處理

方法 說明
public void startDocument() throws SAXException 文檔開始
public void endDocument() throws SAXException 文檔結束
public void startElement(String uri,String localName,String qName,Attributes attr) throws SAXException 元素開始,可以取得元素的名稱和元素的全部屬性
public void endElement(String uri,String localName,String qName) throws SAXException 元素結束,可以取得元素的名稱和元素的全部屬性
public void characters(char[] ch,int start,int length) throws SAXException 元素內容

2.SAX解析器

//定義SAX解析器示例
//假設已導入所需的包
public class parserSAX extends DefaultHandler {

    @Override
    public void startDocument() throws SAXException {  //文檔開始
        System.out.println("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    }

    @Override
    public void endDocument() throws SAXException {  //文檔結束
        System.out.println("\n 讀取結束...");
    }

    @Override
    public void startElement(String uri, String localName, String name, Attributes attr) throws SAXException {
        //元素開始
        System.out.print("<");
        //輸出元素名稱
        System.out.print(name);
        //取得全部的屬性
        if (attr != null) {
            for (int x = 0; x < attr.getLength(); x++) {
                System.out.print(" " + attr.getQName(x)
                        + "=\"" + attr.getValue(x) + "\"");
            }
        }
        System.out.print(">");
    }

    @Override
    public void endElement(String uri, String localName, String name) throws
            SAXException {  //元素結束
        System.out.print("</");
        //輸出元素名稱
        System.out.print(name);
        System.out.print(">");
    }

    @Override
    public void characters(char[] ch, int start, int length) throws
            SAXException{  //取得元素內容
        System.out.print(new String(ch,start,length));  //輸出內容
    }
}

3.使用SAX解析器

//使用SAX解析器示例
//假設已導入所需的包
public class Main {
    public static void main(String[] args) throws Exception {
        //建立SAX解析工廠
        SAXParserFactory fac = SAXParserFactory.newInstance();
        //構造解析器
        SAXParser par = fac.newSAXParser();
        //解析XML使用HANDLER
        par.parse("C:" + File.separator + "SAX.xml", new parserSAX());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章