除了可以使用 SAX和DOM解析XML文件,大家也可以使用Android内置的Pull解析器解析XML文件。Pull解析器的运行方式与 SAX 解析器相似。它提供了类似的事件,如:开始元素和结束元素事件,使用parser.next()可以进入下一个元素并触发相应事件。事件将作为数值代码被发送,因此可以使用一个switch对感兴趣的事件进行处理。当元素开始解析时,调用parser.nextText()方法可以获取下一个Text类型元素的值。
下面列出需要解析的XML文件,保存在Android的assets目录下:
<?xml version="1.0" encoding="UTF-8"?> <persons> <person id="23"> <name>小明</name> <age>30</age> </person> <person id="20"> <name>小强</name> <age>25</age> </person> </persons>
package com.example.xmlpullparse; public class PersonBean { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.example.xmlpullparse; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import com.example.xmlsaxparse.R; import android.app.Activity; import android.os.Bundle; import android.util.Xml; import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; private String notice = ""; private InputStream inStream; private PersonBean currentPerson = null; private List<PersonBean> persons = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.test); try { inStream = this.getAssets().open("test.xml"); } catch (IOException e) { e.printStackTrace(); } persons = readXML(inStream); for (int i = 0; i < persons.size(); i++) { notice += persons.get(i).getName() + persons.get(i).getAge(); } textView.setText(notice); } public List<PersonBean> readXML(InputStream inStream) { XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(inStream,"UTF-8"); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理 persons = new ArrayList<PersonBean>(); break; case XmlPullParser.START_TAG:// 开始元素事件 String name = parser.getName(); if (name.equalsIgnoreCase("person")) { currentPerson = new PersonBean(); currentPerson.setId(Integer.valueOf(parser .getAttributeValue(null,"id"))); } else if (currentPerson != null) { if (name.equalsIgnoreCase("name")) { currentPerson.setName(parser.nextText());// 如果后面是Text元素,即返回它的值 } else if (name.equalsIgnoreCase("age")) { currentPerson.setAge(new Short(parser.nextText())); } } break; case XmlPullParser.END_TAG:// 结束元素事件 if (parser.getName().equalsIgnoreCase("person") && currentPerson != null) { persons.add(currentPerson); currentPerson = null; } break; } eventType = parser.next(); } inStream.close(); return persons; } catch (Exception e) { e.printStackTrace(); } return null; } }原文链接:https://www.f2er.com/xml/298909.html