XML介绍:Extensible Markup Language,即可扩展标记语言
SAX(Simple API for XML) 使用流式处理的方式,它并不记录所读内容的相关信息。它是一种以事件为驱动的XML API,解析速度快,占用内存少。使用回调函数来实现。 缺点是不能倒退。
DOM(Document Object Model) 是一种用于XML文档的对象模型,可用于直接访问XML文档的各个部分。它是一次性全部将内容加载在内存中,生成一个树状结构,它没有涉及回调和复杂的状态管理。 缺点是加载大文档时效率低下。
Pull内置于Android系统中。也是官方解析布局文件所使用的方式。Pull与SAX有点类似,都提供了类似的事件,如开始元素和结束元素。不同的是,SAX的事件驱动是回调相应方法,需要提供回调的方法,而后在SAX内部自动调用相应的方法。而Pull解析器并没有强制要求提供触发的方法。因为他触发的事件不是一个方法,而是一个数字。它使用方便,效率高。
解析代码:
public class SAXForHandler extends DefaultHandler {
/**
* -----------------SAX解析XML----------------------
*/
private static final String TAG = "SAXForHandler";
private List persons;
private String perTag;// 通过此变量,记录前一个标签的名称
Person person;// 记录当前Person
public List getPersons() {
return persons;
}
@Override
public void characters(char[] ch, int start, 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(perTag)) {
person.setName(data);
}
else if ("age".equals(perTag)) {
person.setAge(new Short(data));
}
super.characters(ch, start, length);
}
@Override
public void endDocument() throws SAXException {
Log.i(TAG, "***endDocument()***");
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
Log.i(TAG, qName + "***endElement()***");
if ("person".equals(localName)) {
persons.add(person);
person = null;
}
perTag = null;
super.endElement(uri, localName, qName);
}
@Override
public void startDocument() throws SAXException {
persons = new ArrayList();
Log.i(TAG, "***startDocument()***");
super.startDocument();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {//localName标签名,fullName带命名空间的标签名,attribute存放该标签所有属性
if ("person".equals(localName)) {
for (int i = 0; i < attributes.getLength(); i++) {
Log.i(TAG, "attributeName:" + attributes.getLocalName(i)
+ "_attribute_Value:" + attributes.getValue(i));
person = new Person();
person.setId(Integer.valueOf(attributes.getValue(i)));
// person.setId(Integer.parseInt(attributes.getValue(i)));
}
}
perTag = localName;
Log.i(TAG, qName + "***startElement()***");
super.startElement(uri, localName, qName, attributes);
}
}
使用SAX解析:
/**
* *****************************使用SAX解析XML文件*******************
* 输入流是指向程序中读入数据
* @throws Throwable
*/
public void testSAXGetPersons() throws Throwable {
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("person.xml");
SAXForHandler saxForHandler = new SAXForHandler();
/**
* 用工廠模式解析XML
*/
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
saxParser.parse(inputStream, saxForHandler);
// 第二种方式解析XML
// XMLReader xmlReader = saxParser.getXMLReader();
// xmlReader.setContentHandler(handler);
// xmlReader.parse(new InputSource(inputStream));
List persons = saxForHandler.getPersons();
inputStream.close();
for (Person person : persons) {
Log.i(TAG, person.toString());
}
}
public class DomPersonService {
/**
* @param inStream
* @return
* @throws Exception
*/
public static List getPersons(InputStream inStream)
throws Exception {
List persons = new ArrayList();
/**
* 文檔的解析
*/
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(new Short(age));
}
}
}
persons.add(person);
}
inStream.close();
return persons;
}
}
使用DOM解析XML文件
public void testDOMGetPersons() throws Throwable {
InputStream inStream = this.getClass().getClassLoader()
.getResourceAsStream("person.xml");
List persons = DomPersonService.getPersons(inStream);
for (Person person : persons) {
Log.i(TAG, person.toString());
}
}
public class PullPersonService {
/**
* ------------------------使用PULL解析XML-----------------------
* @param inStream
* @return
* @throws Exception
*/
public static List getPersons(InputStream inStream)
throws Exception {
Person person = null;
List persons = null;
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(inStream, "UTF-8");
int event = pullParser.getEventType();// 觸發第一個事件
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
persons = new ArrayList();
break;
case XmlPullParser.START_TAG:
if ("person".equals(pullParser.getName())) {
int id = new Integer(pullParser.getAttributeValue(0));
person = new Person();
person.setId(id);
}
if (person != null) {
if ("name".equals(pullParser.getName())) {
person.setName(pullParser.nextText());
}
if ("age".equals(pullParser.getName())) {
person.setAge(new Short(pullParser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:
if ("person".equals(pullParser.getName())) {
persons.add(person);
person = null;
}
break;
}
event = pullParser.next();
}
return persons;
}
}
PULL解析XML文件
public void testPullGetPersons() throws Throwable {
InputStream inStream = this.getClass().getClassLoader()
.getResourceAsStream("person.xml");
List persons = PullPersonService.getPersons(inStream);
for (Person person : persons) {
Log.i(TAG, person.toString());
}
}