本文使用SAX來解析XML,在Android裡面可以使用SAX和DOM,DOM需要把整個XML文件讀入內存再解析,比較消耗內存,而SAX基於事件驅動的處理方式,可以在各節點觸發回調函數,不過SAX適合節點結構簡單的XML文檔,復雜的XML文檔在後期的節點深度處理會有點麻煩。
本文要解析的test.xml文件如下:
XML/HTML代碼
- <?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定義各種回調函數,“條件符合”的時候觸發這些回調函數。
Java代碼
- 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的操作。生成XML的結果如下:
上圖是讀取各節點之後,使用XmlSerializer重新組合並輸出XML字符串。本文的main.xml代碼如下:
XML/HTML代碼
- <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 android:layout_height="wrap_content"
- android:layout_width="fill_parent" android:text="生成XML" android:id="@+id/btnOutput">
- <edittext android:text="@+id/EditText01" android:id="@+id/EditText01"
- android:layout_width="fill_parent" android:layout_height="fill_parent">
testSAX.java的源碼如下:
Java代碼
- package com.testSAX;
-
- import java.io.StringWriter;
-
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
-
- import org.xml.sax.InputSource;
- import org.xml.sax.XMLReader;
- import org.xmlpull.v1.XmlSerializer;
-
- import android.app.Activity;
- import android.os.Bundle;
-
- import android.util.Xml;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
-
- public class testSAX extends Activity {
- /** Called when the activity is first created. */
- Button btnSAX, btnOutput;
- EditText memo;
- SAXHandler handler = new SAXHandler();
-
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnSAX = (Button) this.findViewById(R.id.btnSAX);
- btnSAX.setOnClickListener(new ClickEvent());
- btnOutput = (Button) this.findViewById(R.id.btnOutput);
- btnOutput.setOnClickListener(new ClickEvent());
- memo = (EditText) this.findViewById(R.id.EditText01);
- }
-
- class ClickEvent implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- if (v == btnSAX) {//解析XML,並保存標記,屬性等值
- try {
- 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)));
- } catch (Exception ee) {}
- } else if (v == btnOutput) {//生成XML
- try {
- XmlSerializer serializer = Xml.newSerializer();
- StringWriter writer = new StringWriter();
- try {
- serializer.setOutput(writer);
- serializer.startDocument("UTF-8",true);
-
- for(int i=0;i<handler.getkeys().size();i++)
- {
- if(handler.GetKeys().get(i).equals("startTag"))
- {
- serializer.startTag("", (String) handler.GetValues().get(i));
- }else if(handler.GetKeys().get(i).equals("Attr")){
- String[] str= (String[]) handler.GetValues().get(i);
- serializer.attribute("",str[0],str[1]);
- }else if(handler.GetKeys().get(i).equals("text"))
- serializer.text((String)handler.GetValues().get(i));
- else if(handler.GetKeys().get(i).equals("endTag"))
- {
- serializer.endTag("", (String) handler.GetValues().get(i));
- }
- }
- serializer.endDocument();
- String text=writer.toString();
- text=text.replace("><", ">/r/n<");
- memo.setText(text);//輸出到文本框
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- } catch (Exception e) {}
- }
- }
- }
- }