歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Sax方法讀取xml文件

Android Sax方法讀取xml文件

日期:2017/3/1 10:52:42   编辑:Linux編程
SAX(Simple API for XML)提供了一種基於事件的處理思路,不需要裝載、遍歷整個XML文件,只要發現你所關心的標簽或數據,就可以隨時停止解析。

1. xml讀取代碼,繼承DefaultHandler(內含解析XML文檔中產生的各種類型的事件的空實現,只需重寫用到的事件即可)。
事件處理的順序:一般在 startDocument() 初始化工作,在 endDocument() 中收尾的處理工作;startElement() - characters() - endDocument() 是一個XML節點讀取的過程,startElement() 用來初始判斷,characters() 獲取節點的字符數據,endDocument() 將數據寫入數據結構。
  1. package mytest.xml;
  2. import org.xml.sax.Attributes;
  3. import org.xml.sax.SAXException;
  4. import org.xml.sax.helpers.DefaultHandler;
  5. public class XmlHandler extends DefaultHandler {
  6. private String _name = null, _address = null;
  7. private int _id = 0, _age = 0, _flag = 0;
  8. private String _str = "";
  9. public String getString() {
  10. return _str;
  11. }
  12. @Override
  13. // 開始處理文檔時觸發
  14. public void startDocument() throws SAXException {
  15. super.startDocument();
  16. }
  17. @Override
  18. // 開始處理元素時觸發
  19. public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
  20. if(localName.equalsIgnoreCase("Student"))
  21. {
  22. String tmp = attributes.getValue("id");
  23. if(tmp != null) _id = Integer.parseInt(tmp);
  24. }
  25. else if(localName.equalsIgnoreCase("name"))
  26. _flag = 1;
  27. else if(localName.equalsIgnoreCase("age"))
  28. _flag = 2;
  29. else if(localName.equalsIgnoreCase("address"))
  30. _flag = 3;
  31. }
  32. @Override
  33. // 處理元素字符內容時觸發
  34. public void characters(char[] ch, int start, int length) throws SAXException {
  35. String tmp = new String(ch, start, length);
  36. if(_flag == 1) _name = tmp;
  37. else if(_flag == 2) _age = Integer.parseInt(tmp);
  38. else if(_flag == 3) _address = tmp;
  39. _flag = 0;
  40. super.characters(ch, start, length);
  41. }
  42. @Override
  43. // 元素處理結束時觸發
  44. public void endElement(String uri, String localName, String name)
  45. throws SAXException {
  46. if(localName.equalsIgnoreCase("Student"))
  47. {
  48. this._str += this._name + "\n" + "Id: " + this._id + "\nAge: " + this._age +
  49. "\nAddress: " + this._address + "\n\n";
  50. }
  51. super.endElement(uri, localName, name);
  52. }
  53. @Override
  54. // 文檔處理結束時觸發
  55. public void endDocument() throws SAXException {
  56. super.endDocument();
  57. }
  58. }
2. 主activity
  1. package mytest.xml;
  2. import java.io.File;
  3. import javax.xml.parsers.SAXParser;
  4. import javax.xml.parsers.SAXParserFactory;
  5. import Android.app.Activity;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.view.View.OnClickListener;
  9. import android.widget.Button;
  10. import android.widget.TextView;
  11. public class TestActivity extends Activity {
  12. /** Called when the activity is first created. */
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. Button btn = (Button)this.findViewById(R.id.xmlReadBtn);
  18. btn.setOnClickListener(new OnClickListener() {
  19. @Override
  20. public void onClick(View args0) {
  21. TextView text = (TextView)findViewById(R.id.xmlPathEdit);
  22. String str = readXml(text.getText().toString());
  23. text = (TextView)findViewById(R.id.shownText);
  24. if(str != null)
  25. text.setText(str);
  26. }
  27. });
  28. }
  29. private String readXml(String filepath) {
  30. String str = null;
  31. File f = new File(filepath);
  32. if(f.exists())
  33. {
  34. SAXParserFactory factory = SAXParserFactory.newInstance();
  35. try {
  36. SAXParser sp = factory.newSAXParser();
  37. XmlHandler handler = new XmlHandler();
  38. sp.parse(f, handler);
  39. str = handler.getString();
  40. } catch(Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. return str;
  45. }
  46. }
3. 頁面代碼
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:weightSum="1">
  7. <TextView android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:text="Path:"
  10. android:textSize="8pt"
  11. android:gravity="left" />
  12. <LinearLayout android:layout_height="wrap_content"
  13. android:orientation="horizontal" android:layout_width="fill_parent">
  14. <EditText android:id="@+id/xmlPathEdit"
  15. android:layout_width="278dp"
  16. android:layout_height="wrap_content"/>
  17. <Button android:layout_height="40dp"
  18. android:text="OK"
  19. android:layout_width="wrap_content"
  20. android:id="@+id/xmlReadBtn" />
  21. </LinearLayout>
  22. <TextView android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:id="@+id/shownText"
  25. android:textSize="8pt"
  26. android:gravity="left"
  27. android:layout_weight="0.86"/>
  28. </LinearLayout>
4. 讀取的xml文件結構
  1. <?xml version="1.0" encoding="utf-8" standalone="yes"?>
  2. <Students count="2">
  3. <Student id="0">
  4. <name>Bill</name>
  5. <age>13</age>
  6. <address>ABCDEFG</address>
  7. </Student>
  8. <Student id="1">
  9. <name>Nancy</name>
  10. <age>17</age>
  11. <address>HIJKLMN</address>
  12. </Student>
  13. </Students>
Copyright © Linux教程網 All Rights Reserved