Android開發進階(一)XML文件解析之SAX模式解析

SAX解析XML:html

SAX基本原理:java

採用事件驅動解析XML文件,以流式方式逐行的去讀,它不須要解析完整個文檔,在按內容順序解析文檔的過各中,SAX會判斷當前講到的字符是否合法XML語法中的某部分,若是符合就觸發事件(例如startDocument()、endDocument()諸如此類的事件),它的特色是不會記錄前面所碰到的標籤,而且它是一個解析速度快而且佔用內存少的XML解析器,web

SAX解析步驟:數組

一、從SAXPraserFactory中建立一個新的實例app

二、再從SAXParserFactory裏獲得一個新的SAX解析器對象SAXParseride

三、再調用SAXParser對象的.parse()方法裏面帶兩個參數一個是輸入流一個是DefaultHandler對象這樣就能夠了。而DefaultHandler是實現了ContentHandler接口的。ContentHandler接口中定義了一系列的方法事件:諸如:oop

[java] view plaincopyprint?測試

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_1 height=14 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">ui

  1. public abstract void startDocument ()   this


方法做用:文檔解析觸發此事件

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_2 height=14 name=ZeroClipboardMovie_2 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=2&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public abstract void endDocument ()   


方法做用:文檔解析結束時觸發此事件

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_3 height=14 name=ZeroClipboardMovie_3 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=3&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public abstract void startElement (String uri, String localName, String qName, Attributes atts)   


方法做用:當開始讀取元素時觸發此事件

參數說明:

uri:命名空間

localName:不帶命名空間的前綴的標籤名

qName:不按期命名空間前綴的標籤名

atts:獲得全部的屬性各和相應的值

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_4 height=14 name=ZeroClipboardMovie_4 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=4&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public abstract void endElement (String uri, String localName, String qName)   


方法做用:讀取的標籤結束時觸發此事件,參數說明同上

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_5 height=14 name=ZeroClipboardMovie_5 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=5&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public abstract void characters (char[] ch, int start, int length)   


方法做用:用來處理在XML文件中讀到的內容

參數說明:

ch:用於存放文件的內容

start:所讀到的字符串在這個數組中的起始位置

length:長度

咱們能夠用new String(ch,start,length)來獲取內容

 

下面以person.xml文件爲例採用SAX解析器來模擬解析這個XML文檔:

[html] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_6 height=14 name=ZeroClipboardMovie_6 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=6&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. <?xml version="1.0" encoding="UTF-8"?>  

  2.   

  3. <persons>  

  4.   

  5.        <person id="23">  

  6.   

  7.               <name>李明</name>  

  8.   

  9.               <age>30</age>  

  10.   

  11.        </person>  

  12.   

  13.        <person id="20">  

  14.   

  15.               <name>李向梅</name>  

  16.   

  17.               <age>25</age>  

  18.   

  19.        </person>  

  20.   

  21. </persons>  


 

解析person.xml觸發的事件爲:

讀到的標籤及內容

觸發事件

{文檔開始}

startDocument()

<persons>

startElement(, "persons", null, "{Attributes}")

"\n\t"

characters("<persons>...</persons>", "12", "2")

<person>

startElement(, "person", null, "{Attributes}")

"\n\t\t"

characters("<persons>...</persons>", "31", "3")

<name>

startElement(, "name", null, "{Attributes}")

"李明"

characters("<persons>...</persons>", "40", "2")

</name>

endElement("", "name", null)

"\n\t\t"

characters("<persons>...</persons>", "50", "3")

<age>

startElement(, "age", null, "{Attributes}")

"30"

characters("<persons>...</persons>", "58", "2")

</age>

endElement("", "age", null)

"\n\t"

characters("<persons>...</persons>", "67", "2")

</person>

endElement("", "person", null)

"\n\t"

characters("<persons>...</persons>", "79", "2")

又重複<person>

….

{文檔結束}

endDocument()

 

實例1:讀取XML文件裏的內容把這些內容構形成一個Person對象,而後讀取這個XML文檔裏內容將其Person對象添加到一個List集合裏:

Person類:

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_7 height=14 name=ZeroClipboardMovie_7 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=7&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public class Person {  

  2.   

  3.    

  4.   

  5.     private Integer id;  

  6.   

  7.     private String name;  

  8.   

  9.     private short age;  

  10.   

  11.       

  12.   

  13.     public Integer getId() {  

  14.   

  15.        return id;  

  16.   

  17.     }  

  18.   

  19.     public void setId(Integer id) {  

  20.   

  21.        this.id = id;  

  22.   

  23.     }  

  24.   

  25.    

  26.   

  27.     public String getName() {  

  28.   

  29.        return name;  

  30.   

  31.     }  

  32.   

  33.     public void setName(String name) {  

  34.   

  35.        this.name = name;  

  36.   

  37.     }  

  38.   

  39.    

  40.   

  41.     public short getAge() {  

  42.   

  43.        return age;  

  44.   

  45.     }  

  46.   

  47.     public void setAge(short age) {  

  48.   

  49.        this.age = age;  

  50.   

  51.     }  

  52.   

  53.    

  54.   

  55.     @Override  

  56.   

  57.     public String toString() {  

  58.   

  59.        return "Person [age=" + age + ", id=" + id + ", name=" + name + "]";  

  60.   

  61.     }  

  62.   

  63.    

  64.   

  65. }  


 

業務bean:

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_8 height=14 name=ZeroClipboardMovie_8 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=8&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public class SAXPersonService {   

  2.   

  3. public static List<Person> readXml(InputStream inputStream)  

  4.   

  5.            throws Exception {  

  6.   

  7.    

  8.   

  9.        // 獲得一個SAXParserFactory對象  

  10.   

  11.        SAXParserFactory spf = SAXParserFactory.newInstance();  

  12.   

  13.        // SAX解析對象  

  14.   

  15.        SAXParser saxParser = spf.newSAXParser();  

  16.   

  17.    

  18.   

  19.        // ContentHandler對象  

  20.   

  21.        XMLContentHandler handler = new XMLContentHandler();  

  22.   

  23.    

  24.   

  25.        // 開始解析  

  26.   

  27.        saxParser.parse(inputStream, handler);  

  28.   

  29.        // 關閉流  

  30.   

  31.        inputStream.close();  

  32.   

  33.    

  34.   

  35.        return handler.getPersons();  

  36.   

  37.    

  38.   

  39.     }  

  40.   

  41. }  


 

XMLContentHandler繼承自DefalutHander而DefaultHandler實現ContentHandler接口

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_9 height=14 name=ZeroClipboardMovie_9 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=9&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. /** 

  2.  

  3.  * 繼承於DefaultHandler  這個類也是實現ContentHandler 

  4.  

  5.  * @author Administrator 

  6.  

  7.  * 

  8.  

  9.  */  

  10.   

  11. public class XMLContentHandler extends DefaultHandler {  

  12.   

  13.    

  14.   

  15.     private List<Person> persons;  

  16.   

  17.     private Person person;  

  18.   

  19.     private String preTag;//當前標記  

  20.   

  21.    

  22.   

  23.     public List<Person> getPersons() {  

  24.   

  25.        return persons;  

  26.   

  27.     }  

  28.   

  29.       

  30.   

  31.     /** 

  32.  

  33.      * 文檔開始 

  34.  

  35.      */  

  36.   

  37.     public void startDocument() throws SAXException {  

  38.   

  39.        persons = new ArrayList<Person>();  

  40.   

  41.     }  

  42.   

  43.    

  44.   

  45.     /** 

  46.  

  47.      * 讀取的文檔內容 

  48.  

  49.      */  

  50.   

  51.     public void characters(char[] ch, int start, int length)  

  52.   

  53.            throws SAXException {  

  54.   

  55.    

  56.   

  57.        if (person != null) {  

  58.   

  59.            String data = new String(ch, start, length);  

  60.   

  61.            // 判斷前面的元素是不是"name"  

  62.   

  63.            if ("name".equals(preTag)) {  

  64.   

  65.               person.setName(data);  

  66.   

  67.            } else if ("age".equals(preTag)) {  

  68.   

  69.               person.setAge(new Short(data));  

  70.   

  71.            }  

  72.   

  73.        }  

  74.   

  75.    

  76.   

  77.     }  

  78.   

  79.       

  80.   

  81.     /** 

  82.  

  83.      * 元素開始 

  84.  

  85.      */  

  86.   

  87.     public void startElement(String uri, String localName, String qName,  

  88.   

  89.            Attributes attributes) throws SAXException {  

  90.   

  91.        // 判斷目前解析到的元素是否等於"person"  

  92.   

  93.        if ("person".equals(localName)) {  

  94.   

  95.            person = new Person();  

  96.   

  97.            // person.setId(Integer.parseInt(attributes.getValue(0)));  

  98.   

  99.            person.setId(Integer.parseInt(attributes.getValue("""id")));  

  100.   

  101.        }  

  102.   

  103.        // 當前元素  

  104.   

  105.        preTag = localName;  

  106.   

  107.     }  

  108.   

  109.    

  110.   

  111.     /** 

  112.  

  113.      * 解析完一個元素後就把這個元素加到List裏 

  114.  

  115.      */  

  116.   

  117.     public void endElement(String uri, String localName, String qName)  

  118.   

  119.            throws SAXException {  

  120.   

  121.        if ("person".equals(localName) && person != null) {  

  122.   

  123.            persons.add(person);  

  124.   

  125.            person = null;  

  126.   

  127.        }  

  128.   

  129.        //再將這個當前元素設爲null  

  130.   

  131.        preTag=null;  

  132.   

  133.     }  

  134.   

  135. }  


 

測試:

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_10 height=14 name=ZeroClipboardMovie_10 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=10&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

  1. public class SAXPersonServiceTest extends AndroidTestCase {  

  2.   

  3.    

  4.   

  5.     private static final String TAG = "LogTest";  

  6.   

  7.     public void testSAXReadXml() throws Exception {  

  8.   

  9.        //從資源文件中獲取輸入流  

  10.   

  11.        InputStream inputStream = SAXPersonServiceTest.class.getClassLoader()  

  12.   

  13.               .getResourceAsStream("itcast.xml");  

  14.   

  15.        List<Person> list = SAXPersonService.readXml(inputStream);  

  16.   

  17.        for (Person person : list) {  

  18.   

  19.            System.out.println(person);  

  20.   

  21.        }  

  22.   

  23.     }  

  24.   

  25. }  

  26.   

  27. 如需轉載引用請註明出處:<a href="http://blog.csdn.net/jiahui524">http://blog.csdn.net/jiahui524</a>  

[java] view plaincopyprint?

<EMBED style="-webkit-animation: playerInserted 0.001s" id=ZeroClipboardMovie_11 height=14 name=ZeroClipboardMovie_11 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=29 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=11&width=29&height=14" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">

相關文章
相關標籤/搜索