android XML解析器全解案例

1.使用pull解析

 package com.example.myxml;

 import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log;
import android.util.Xml; public class Pullparser { public static List<Person> getPerson(InputStream inStream) throws Exception {
List<Person> psonList = new ArrayList<Person>();
Person person = null;
XmlPullParser xmlParse = Xml.newPullParser();
try {
xmlParse.setInput(inStream, "utf-8");
int evnType = xmlParse.getEventType();
while (evnType != XmlPullParser.END_DOCUMENT) {
switch (evnType) {
case XmlPullParser.START_TAG:
String tag = xmlParse.getName();
if (tag.equalsIgnoreCase("person")) {
person = new Person();
person.setId(Integer.parseInt(xmlParse.getAttributeValue(0)));
} else if (person != null) {
// parse after tag
if (tag.equalsIgnoreCase("name")) {
person.setName(xmlParse.nextText());
} else if (tag.equalsIgnoreCase("age")) {
person.setAge(xmlParse.nextText());
}
}
break;
case XmlPullParser.END_TAG:
if (xmlParse.getName().equalsIgnoreCase("person")
&& person != null) {
psonList.add(person);
person = null;
}
break;
default:
break;
}
evnType = xmlParse.next();
}
} catch (Exception e) {
}
return psonList;
}
}

2.使用DOM解析

package com.example.myxml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import android.annotation.SuppressLint; public class DOMparser { @SuppressLint("UseValueOf")
public static List<Person> parse(InputStream inStream) throws Exception {
List<Person> persons = new ArrayList<Person>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inStream);
Element root = document.getDocumentElement();
NodeList personNodes = root.getElementsByTagName("person");
for (int i = 0; i < personNodes.getLength(); i++) {
Element personElement = (Element) personNodes.item(i);
int id = new Integer(personElement.getAttribute("id"));
Person person = new Person();
person.setId(id);
NodeList childNodes = personElement.getChildNodes();
for (int y = 0; y < childNodes.getLength(); y++) {
if (childNodes.item(y).getNodeType() == Node.ELEMENT_NODE) {
if ("name".equals(childNodes.item(y).getNodeName())) {
String name = childNodes.item(y).getFirstChild().getNodeValue();
person.setName(name);
}else if ("age".equals(childNodes.item(y).getNodeName())) {
String age = childNodes.item(y).getFirstChild().getNodeValue();
person.setAge(age);
}
}
}
persons.add(person);
}
inStream.close();
return persons;
}
}

3.使用SAX解析

package com.example.myxml;

import java.util.ArrayList;
import java.util.List; import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import android.annotation.SuppressLint; public class SAXparser extends DefaultHandler {
private List<Person> persons;
private Person person;
private String preTAG; @Override
public void startDocument() throws SAXException {
persons = new ArrayList<Person>();
} @Override
public void characters(char[] ch, int start, int length)throws SAXException {
if (person != null) {
String data = new String(ch, start, length);
if ("name".equals(preTAG)) {
person.setName(data);
} else if ("age".equals(preTAG)) {
person.setAge(data);
}
}
} @SuppressLint("UseValueOf")
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("person".equals(localName)) {
person = new Person();
person.setId(new Integer(attributes.getValue(0)));
}
preTAG = localName;
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("person".equals(localName) && person != null) {
persons.add(person);
person = null;
}
preTAG = null;
} public List<Person> getPersons() {
return persons;
}
}

案例辅助代码

xML文件

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>张三</name>
<age>54</age>
</person>
<person id="20">
<name>小明</name>
<age>266</age>
</person>
</persons>

读取本地XML文件流

package com.example.myxml;

import java.io.InputStream;
import java.util.List; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends ActionBarActivity {
TextView resultView;
List<Person> personList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); resultView = (TextView) findViewById(R.id.result);
InputStream inStream = MainActivity.class.getClassLoader().getResourceAsStream("personxml.xml");
// SAX_Parser(inStream);
// DOM_Parser(inStream);
PULL_Parser(inStream);
visity();
} private void PULL_Parser(InputStream inStream) {
try {
personList= Pullparser.getPerson(inStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private void DOM_Parser(InputStream inStream) {
try {
personList = DOMparser.parse(inStream);
} catch (Exception e) {
e.printStackTrace();
}
} private void SAX_Parser(InputStream inStream) {
try {
// 得到SAX解析器的工厂实例
SAXParserFactory spf = SAXParserFactory.newInstance();
// 从SAX工厂实例中获得SAX解析器
SAXParser saxParser = spf.newSAXParser();
SAXparser handler = new SAXparser();
saxParser.parse(inStream, handler);
inStream.close(); personList = handler.getPersons();
} catch (Exception e) {
}
}
public void visity(){
if(personList!=null){
StringBuilder sb = new StringBuilder();
for (Person person : personList) {
sb.append(person.toString()).append("\n");
}
resultView.setText(sb.toString());
}else{
Toast.makeText(getApplicationContext(), "null", 0).show();
} }
}
上一篇:JSP01


下一篇:forfiles