SAX(Simple API for XML)提供了一种基于事件的处理思路,不需要装载、遍历整个XML文件,只要发现你所关心的标签或数据,就可以随时停止解析。
1. xml读取代码,继承DefaultHandler(内含解析XML文档中产生的各种类型的事件的空实现,只需重写用到的事件即可)。
事件处理的顺序:一般在 startDocument() 初始化工作,在 endDocument() 中收尾的处理工作;startElement() - characters() - endDocument() 是一个XML节点读取的过程,startElement() 用来初始判断,characters() 获取节点的字符数据,endDocument() 将数据写入数据结构。
package mytest.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XmlHandler extends DefaultHandler {
private String _name = null, _address = null;
private int _id = 0, _age = 0, _flag = 0;
private String _str = "";
public String getString() {
return _str;
}
@Override
// 开始处理文档时触发
public void startDocument() throws SAXException {
super.startDocument();
}
@Override
// 开始处理元素时触发
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("Student"))
{
String tmp = attributes.getValue("id");
if(tmp != null) _id = Integer.parseInt(tmp);
}
else if(localName.equalsIgnoreCase("name"))
_flag = 1;
else if(localName.equalsIgnoreCase("age"))
_flag = 2;
else if(localName.equalsIgnoreCase("address"))
_flag = 3;
}
@Override
// 处理元素字符内容时触发
public void characters(char[] ch, int start, int length) throws SAXException {
String tmp = new String(ch, start, length);
if(_flag == 1) _name = tmp;
else if(_flag == 2) _age = Integer.parseInt(tmp);
else if(_flag == 3) _address = tmp;
_flag = 0;
super.characters(ch, start, length);
}
@Override
// 元素处理结束时触发
public void endElement(String uri, String localName, String name)
throws SAXException {
if(localName.equalsIgnoreCase("Student"))
{
this._str += this._name + "\n" + "Id: " + this._id + "\nAge: " + this._age +
"\nAddress: " + this._address + "\n\n";
}
super.endElement(uri, localName, name);
}
@Override
// 文档处理结束时触发
public void endDocument() throws SAXException {
super.endDocument();
}
}
2. 主activity
package mytest.xml;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)this.findViewById(R.id.xmlReadBtn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View args0) {
TextView text = (TextView)findViewById(R.id.xmlPathEdit);
String str = readXml(text.getText().toString());
text = (TextView)findViewById(R.id.shownText);
if(str != null)
text.setText(str);
}
});
}
private String readXml(String filepath) {
String str = null;
File f = new File(filepath);
if(f.exists())
{
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser sp = factory.newSAXParser();
XmlHandler handler = new XmlHandler();
sp.parse(f, handler);
str = handler.getString();
} catch(Exception e) {
e.printStackTrace();
}
}
return str;
}
}
3. 页面代码
<?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"
android:weightSum="1">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Path:"
android:textSize="8pt"
android:gravity="left" />
<LinearLayout android:layout_height="wrap_content"
android:orientation="horizontal" android:layout_width="fill_parent">
<EditText android:id="@+id/xmlPathEdit"
android:layout_width="278dp"
android:layout_height="wrap_content"/>
<Button android:layout_height="40dp"
android:text="OK"
android:layout_width="wrap_content"
android:id="@+id/xmlReadBtn" />
</LinearLayout>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/shownText"
android:textSize="8pt"
android:gravity="left"
android:layout_weight="0.86"/>
</LinearLayout>
4. 读取的xml文件结构
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Students count="2">
<Student id="0">
<name>Bill</name>
<age>13</age>
<address>ABCDEFG</address>
</Student>
<Student id="1">
<name>Nancy</name>
<age>17</age>
<address>HIJKLMN</address>
</Student>
</Students>