SAX之:SAXParserFactory與SAXParser


      SAX是Simple API for XML的簡稱,在Android里面提供對XML文件的解析接口方法,如果給我們一個XML文件,要求把里面我們關心的數據解析出來,我們就可以使用SAX技術,在具體使用中,會對XML文件的每一個字符逐一讀取並出發相應事件,也就是說,SAX技術是事件驅動的。比如startDocument,startElement,characters,endElement等等下面是一個案例。

實例源碼:

 1 public List<Person> getPersons(InputStream inStream) throws Throwable
2
3 {
4 SAXParserFactory factory = SAXParserFactory.newInstance();
5 SAXParser parser = factory.newSAXParser();
6 //自定義擴展自DefaultHandler的子類,覆寫一些解析XML時我們需要的方法
7 PersonParser personParser = new PersonParser();
8 parser.parse(inStream, personParser);
9 //使用完傳進來的輸入流后就把它關閉
10 inStream.close();
11 return personParser.getPersons();
12
13 }

SAXParserFactory 相關介紹:

定義了一個API工廠,使得應用程序可以配置和獲得一個基於SAX(Simple API for XML

)的解析器,從而能夠解析XML文檔( 原文: Defines a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents. )

它的構造器是受保護的,因而只能用newInstance()方法獲得實例( Protected constructor to force use of newInstance(). )

SAXParser相關介紹:

定義了一個繼承自XMLReader類的API,其構造器也是受保護的,通過newSAXParser() 方法獲得實例,可以把各種數據源作為解析用的XML(這個方法就是public void parse (InputSource is, DefaultHandler dh)),這些輸入數據源包括輸入流,文件,URL以及SAX輸入資源。(Defines the API that wraps an XMLReader implementation class , An instance of this class can be obtained from the newSAXParser() method. Once an instance of this class is obtained, XML can be parsed from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources. )

關於SAX更多使用信息,還會撰文。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM