dom解析:
public class DOMPersonService
{
public static List<Person> readXml(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();
//获取所有"pre:person"节。点
NodeList nodes = root.getElementsByTagName("pre:person");
for(int i = 0 ;i < nodes.getLength();i++)
{
Element personElement = (Element)nodes.item(i);
Person person =new Person();
person.setId(Integer.valueOf(personElement.getAttribute("id")));
NodeList childNodes = personElement.getChildNodes();
for(int j = 0;j<childNodes.getLength();j++)
{
Node childNode = (Node)childNodes.item(j);
if (childNode.getNodeType()==Node.ELEMENT_NODE)
{
Element childElement = (Element)childNode;
if ("name".equals(childElement.getNodeName()))
{
person.setName(childElement.getFirstChild().getNodeValue());
}
else if (("age".equals(childElement.getNodeName())))
{
person.setAge(new Short(childElement.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
return persons;
}
}
调用此类测试:
public class DOMPersonServiceTest extends AndroidTestCase
{
private static final String TAG="PersonServiceTest";
public void testReadXml() throws Exception
{
InputStream inStream=DOMPersonServiceTest.class.getClassLoader().getResourceAsStream("person.xml");
//解析出的xml
List<Person> persons=DOMPersonService.readXml(inStream);
for (Person person : persons)
{
Log.i(TAG, person.toString());
}
}
}
SAX解析:
public class SAXPersonService
{
public static List<Person> readXml(InputStream inStream) throws Exception
{
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser saxParser=spf.newSAXParser();//创建解析器
XMLContentHandler handler=new XMLContentHandler();
saxParser.parse(inStream, handler);
inStream.close();
return handler.getPersons();
}
}
关键是要实现这个方法:
public class XMLContentHandler extends DefaultHandler
{
private static final String TAG = "XMLContentHandler";
private List<Person> persons;
private Person person;
private String preTag;
public List<Person> getPersons()
{
return persons;
}
@Override
public void startDocument() throws SAXException
{
persons = new ArrayList<Person>();
Log.i(TAG, "开始解析...");
}
/**
* uri:命名空间
* localName:不带命名空间前缀的标签名
* qName:带命名空间前缀的标签名
* attributes:属性集合
*/
@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("id")));
}
preTag = localName;
Log.i(TAG, "解析元素:"+localName);
}
/**
* ch[]:内容
* start:其实位置
* length:长度
*/
@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(new Short(data));
}
}
Log.i(TAG, "解析内容:"+new String(ch, start,length));
}
@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;
Log.i(TAG, localName + "解析完毕");
}
@Override
public void endDocument() throws SAXException
{
super.endDocument();
Log.i(TAG, "文档解析完毕");
}
}
调用测试:
public class SAXPersonServiceTest extends AndroidTestCase
{
private static final String TAG="SAXPersonServiceTest";
public void testReadXml() throws Exception
{
InputStream inStream=SAXPersonServiceTest.class.getClassLoader().getResourceAsStream("person.xml");
List<Person> persons=SAXPersonService.readXml(inStream);
for (Person person : persons)
{
Log.i(TAG, person.toString());
}
}
}
3 PULL解析
public class PullPersonService
{
public static List<Person> readXml(InputStream inStream) throws Exception
{
List<Person> persons=null;
XmlPullParser parser=Xml.newPullParser();
parser.setInput(inStream, "UTF-8");
int eventCode=parser.getEventType();
Person person=null;
while(eventCode!=XmlPullParser.END_DOCUMENT)
{
switch (eventCode)
{
case XmlPullParser.START_DOCUMENT: //0 文档开始事件
persons=new ArrayList<Person>();
break;
case XmlPullParser.START_TAG: //2 开始元素
if ("person".equals(parser.getName()))
{
person=new Person();
person.setId(new Integer(parser.getAttributeValue(0)));
}
else if(null!=person)
{
if ("name".equals(parser.getName()))
{
person.setName(parser.nextText());
}
else if("age".equals(parser.getName()))
{
person.setAge(new Short(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG: //结束元素
if ("person".equals(parser.getName())&&person!=null)
{
persons.add(person);
person=null;
}
break;
}
eventCode=parser.next();
}
return persons;
}
}
调用测试
public class PullPersonServiceTest extends AndroidTestCase
{
private static final String TAG="PersonServiceTest";
public void testReadXml() throws Exception
{
InputStream inStream=PullPersonServiceTest.class.getClassLoader().getResourceAsStream("person.xml");
List<Person> persons=PullPersonService.readXml(inStream);
for (Person person : persons)
{
Log.i(TAG, person.toString());
}
}
}
要解析的文件:
person.xml
<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:pre="http://www.baidu.com">
<pre:person id="001">
<name>coolszy</name>
<age>22</age>
</pre:person>
<pre:person id="002">
<name>kuka</name>
<age>22</age>
</pre:person>
</persons>
如果为网络的话,可以直接获得流:
InputStream inputStream = urlConn.getInputStream();
解析的内容存储:
public class Person
{
private Integer id;
private String name;
private Short age;
public Person()
{
super();
}
public Person(Integer id, String name, Short age)
{
super();
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Short getAge()
{
return age;
}
public void setAge(Short age)
{
this.age = age;
}
@Override
public String toString()
{
return "id=" + getId() + ",name=" + getName() + ",age=" + getAge();
}
}