Android提高第七篇之XML解析與產生

來源:互聯網
上載者:User

本文使用SAX來解析XML,在Android裡面可以使用SAX和DOM,DOM需要把整個XML檔案讀入記憶體再解析,比較消耗記憶體,而SAX基於事件驅動的處理方式,可以在各節點觸發回呼函數,不過SAX適合節點結構簡單的XML文檔,複雜的XML文檔在後期的節點深度處理會有點麻煩。

本文要解析的test.xml檔案如下:

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?>   
<test>   
  <title>testSAX</title>   
    <content aa="1" bb="2">   
      <name>hellogv</name>   
      <url>http://blog.csdn.net/hellogv</url>   
    </content> 
</test>  
<?xml version="1.0" encoding="utf-8"?>
<test>
  <title>testSAX</title>
    <content aa="1" bb="2">
      <name>hellogv</name>
      <url>http://blog.csdn.net/hellogv</url>
    </content>
</test> 

解析如上XML的結果如下:

 

使用SAX解析,需要定義SAXParserFactory(使應用程式能夠配置和擷取基於 SAX 的解析器以解析 XML 文檔),SAXParser(從各種輸入源解析 XML),XMLReader(使用回呼函數讀取 XML 文檔),其中XMLReader是個關鍵。XMLReader可以為解析XML定義各種回呼函數,“條件符合”的時候觸發這些回呼函數。

view plaincopy to clipboardprint?
SAXParserFactory factory = SAXParserFactory.newInstance();  
SAXParser parser = factory.newSAXParser();  
XMLReader reader = parser.getXMLReader();  
reader.setContentHandler(handler);  
reader.parse(new InputSource(testSAX.this.getResources()  
        .openRawResource(R.raw.test))); 
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     XMLReader reader = parser.getXMLReader();
     reader.setContentHandler(handler);
     reader.parse(new InputSource(testSAX.this.getResources()
       .openRawResource(R.raw.test)));

在這段代碼裡,XMLReader就調用繼承DefaultHandler的SAXHandler。DefaultHandler已實現ContentHandler, DTDHandler, EntityResolver, ErrorHandler等介面,包含常見讀取XML的操作,具體請看下面的SAXHandler.java源碼。

產生XML的結果如下:

是讀取各節點之後,使用XmlSerializer重新組合并輸出XML字串。

本文的main.xml代碼如下:

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
 
    <Button android:layout_height="wrap_content" 
        android:layout_width="fill_parent" android:id="@+id/btnSAX" 
        android:text="使用SAX解析XML"></Button> 
    <Button android:layout_height="wrap_content" 
        android:layout_width="fill_parent" android:text="產生XML" android:id="@+id/btnOutput"></Button> 
    <EditText android:text="@+id/EditText01" android:id="@+id/EditText01" 
        android:layout_width="fill_parent" android:layout_height="fill_parent"></EditText> 
 
</LinearLayout> 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <Button android:layout_height="wrap_content"
  android:layout_width="fill_parent" android:id="@+id/btnSAX"
  android:text="使用SAX解析XML"></Button>
 <Button android:layout_height="wrap_content"
  android:layout_width="fill_parent" android:text="產生XML" android:id="@+id/btnOutput"></Button>
 <EditText android:text="@+id/EditText01" android:id="@+id/EditText01"
  android:layout_width="fill_parent" android:layout_height="fill_parent"></EditText>

</LinearLayout>
 

SAXHandler.java的源碼如下:

view plaincopy to clipboardprint?
package com.testSAX;  
 
import java.util.ArrayList;  
import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
 
import android.util.Log;  
 
public class SAXHandler extends DefaultHandler{  
        private ArrayList<String> keys = new ArrayList<String>();//儲存欄位名稱  
        private ArrayList<Object> values = new ArrayList<Object>();//儲存值  
        @Override 
        public void startDocument() throws SAXException {  
            super.startDocument();  
 
        }  
 
        @Override 
        public void endDocument() throws SAXException {  
            super.endDocument();  
        }  
 
        @Override 
        public void startElement(String uri, String localName, String qName,  
                Attributes attributes) throws SAXException {  
            //儲存開始標記  
            keys.add("startTag");  
            values.add(localName);  
 
            Log.e("startTag",localName);  
            //儲存屬性值  
            for ( int i = 0; i < attributes.getLength(); i++ ){  
                keys.add("Attr");  
                String[] str=new String[2];  
       &nb

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.