【优点】:解析速度快、占用内存少。特别适用于Android等移动设备。
使用步骤:
①:针对从XML中获取到的信息,需对其建立一个对象(例:Person),存放相关信息
②:新建一个类继承至DefaultHandler(DefaultHandler是已经实现了ContentHandler的接口),提供了相应的方法。
复写以下方法处理:startDocument();
startElement(String uri,String localName,String qName,Attributes attributes);
characters(char[] ch,int start,int length);
endElement(String uri,String qName);
endDocument();
[方法中参数解释]示例:<newii:will>
uri: 命名空间,示例中的newii
localName: 标签名称,示例中的will
qName: 带命名空间的标签名,示例中的newii:will
attributes: 存放该标签的所有属性
ch: 当前读取到的TextNode字节数组
start: 字节开始位置
length: 当前TextNode长度
③:测试需要,建立一个person.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<persons>
<person id="23">
<name>Test</name>
<age>21</age>
</person>
</persons>
④:在应用中通过
InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("person.xml");
加载需要解析的文件,并通过一个SAXParserFactory来创建具体的SAXParser
解析XML有两种形式,需要创建一个XMLReader或直接使用SAXParser
使用XMLReader方式:
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(is));
使用SAXParser方式:
saxParser.parse(is,handler);
【附】:android应用单元测试方法
①:在AndroidManifest.xml中添加节点
<uses-library android:name="android.test.runner" />
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="cn.gzu.xmlparsertest" />
②:建立测试类继承AndroidTestCase
【源代码如下:】
*/
/****************************************【源码】START**************************************************/
//1.Person.java
public class Person { private Integer id; private String name; private short age; public Person() { super(); } public Person(String name,short age) { super(); this.name = name; this.age = age; } public Person(Integer id,String name,short age) { super(); this.id = id; this.name = name; this.age = age; } // getter and setter ... } //2.SAXForHandler.java public class SAXForHandler extends DefaultHandler { private static final String TAG = "SAXForHandler"; private List<Person> persons; // 记录前一个标签的名称 private String preTag; // 记录当前Person对象 Person person; public List<Person> getPersons() { return persons; } @Override public void startDocument() throws SAXException { persons = new ArrayList<Person>(); Log.i(TAG,"********** startDocument execute **********"); } @Override public void startElement(String uri,Attributes attributes) throws SAXException { if("person".equals(localName)){ for(int i=0;i<attributes.getLength();i++){ Log.i(TAG," attributeName :"+attributes.getLocalName(i)+ " attributeValue :"+attributes.getValue(i)); person = new Person(); person.setId(Integer.parseInt(attributes.getValue(i))); } } preTag = localName; Log.i(TAG,"***** startElement execute *****"+qName); } @Override public void characters(char[] ch,int length) throws SAXException { String data = new String(ch,start,length).trim(); if(!"".equals(data.trim())){ Log.i(TAG," content :"+data.trim()); if("name".equals(preTag)){ person.setName(data); }else if("age".equals(preTag)){ person.setAge(new Short(data)); } } } @Override public void endElement(String uri,String qName) throws SAXException { Log.i(TAG,"***** endElement execute *****"+qName); if("person".equals(localName)){ persons.add(person); person = null; } preTag = null; } @Override public void endDocument() throws SAXException { Log.i(TAG,"********** endDocument execute **********"); } } //3.SAXParserUtil.java public class SAXParserUtil { public static List<Person> saxXml (InputStream is) throws Exception{ SAXForHandler saxForHandler = new SAXForHandler(); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); saxParser.parse(is,saxForHandler); List<Person> persons = saxForHandler.getPersons(); is.close(); return persons; } } //4.单元测试类 SAXParserTest.java public class SAXParserTest extends AndroidTestCase { private static final String TAG = "SAXParserTest"; public void testSAXGetPerson() throws Throwable{ InputStream is = this.getClass().getClassLoader().getResourceAsStream("person.xml"); List<Person> persons = SAXParserUtil.saxXml(is); String text = ""; for(Person p:persons){ text = text + "ID: "+p.getId()+" Name: "+p.getName()+" Age: "+p.getAge()+"\n"; } Log.i(TAG,text); } } //5.MainActivity.java public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView main = (TextView) findViewById(R.id.main_content); InputStream is = MainActivity.class.getClassLoader().getResourceAsStream("person.xml"); try { List<Person> persons = SAXParserUtil.saxXml(is); String text = ""; for(Person p:persons){ text = text + "ID: "+p.getId()+" Name: "+p.getName()+" Age: "+p.getAge()+"\n"; } main.setText(text); } catch (Exception e) { e.printStackTrace(); } } }
//6.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.gzu.xmlparsertest" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <uses-library android:name="android.test.runner" /> <activity android:name="cn.gzu.xmlparsertest.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="cn.gzu.xmlparsertest" /> </manifest>/****************************************【源码】END**************************************************/ 原文链接:https://www.f2er.com/xml/297934.html