Pull解析器是通过标签来解析文档,人为的可以控制解析的进度。调用parser.nextText()方法可以获取下一个Text类型节点的值。
package com.example.parse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Xml;
import com.example.bean.Books;
public class PullParser {
private List<Books> l;
private XmlPullParser pullParser;
Books books;
//public List<Books> parse(InputStream is)
public List<Books> parse(InputStream is) {
try {
pullParser = Xml.newPullParser();
// //设置编码格式
pullParser.setInput(is,"utf-8");
//XmlResourceParser pullParser = context.getResources().getXml(id);
//得到pull解析的头
int eventType = pullParser.getEventType();
//判断标题头的类型
while(eventType!=XmlResourceParser.END_DOCUMENT)
{
//
String name = pullParser.getName();
switch (eventType) {
//开始文档ʼ
case XmlResourceParser.START_DOCUMENT:
l = new ArrayList<Books>();
break;
//开始标签
case XmlResourceParser.START_TAG:
//
if("book".equalsIgnoreCase(name))
{
books=new Books();
}
else if("name".equalsIgnoreCase(name))
{
books.setName( pullParser.nextText());
}
else if("author".equalsIgnoreCase(name))
{
books.setAuthor( pullParser.nextText());
}
else if("price".equalsIgnoreCase(name))
{
books.setPrice( pullParser.nextText());
}
break;
//结束标签
case XmlResourceParser.END_TAG:
if("book".equalsIgnoreCase(name))
{
l.add(books);//
books=null;//设置结束
}
break;
}
//下一个
eventType= pullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return l;
}
}