XML解析

// xml,资源解析器,解析本地文件
XmlResourceParser parser = getResources().getXml(R.xml.customer);
try {
int type = parser.getEventType();// 解析到的类型
while (type != XmlResourceParser.END_DOCUMENT) {// 没有解析到结尾,有些地方没有内容为空
if (type == XmlResourceParser.START_TAG) {// 标签开始的地方<
String tagname = parser.getName();// 标签名
if (tagname.equals("student")) {
student = new Student();
student.setId(parser.getAttributeValue(0));
student.setName(parser.getAttributeValue(1));
student.setAge(Integer.parseInt(parser
.getAttributeValue(2)));
students.add(student);
}else if (tagname.equals("teacher")) {
teacher = new Teacher();
teacher.setId(parser.getAttributeValue(0));
teacher.setName(parser.getAttributeValue(1));
teacher.setAge(Integer.parseInt(parser
.getAttributeValue(2)));
teachers.add(teacher);
}else if (tagname.equals("customer")) {
customer = new Customer();
customer.setId(parser.getAttributeValue(0));
customer.setName(parser.getAttributeValue(1));
customer.setAge(Integer.parseInt(parser
.getAttributeValue(2)));
customers.add(customer);
}
}
type = parser.next();// 继续解析
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

 

 

// 自定义一个pull解析的方法
public void parseXmlWithPull(InputStream is) {
// 将Xml流对象解析出来

try {// 实例化一个解析工厂
XmlPullParserFactory parserFactory = XmlPullParserFactory
.newInstance();
// 通过解析工厂得到pull解析器
XmlPullParser pullParser = parserFactory.newPullParser();
// 将连接得到的流媒体进行解析并设置编码类型
pullParser.setInput(is, "utf-8");
// 开始解析
int eventType = pullParser.getEventType();// 解析每一个<>标签,是什么类型(文档结束,开始,标签开始,结束或者null)
while (eventType != XmlPullParser.END_DOCUMENT) {// 不是文档结尾
if (eventType == XmlPullParser.START_TAG) {
String tagname = pullParser.getName();// 标签名
if (tagname.equals("student")) {
student = new Student();
student.setId(pullParser.getAttributeValue(0));
student.setName(pullParser.getAttributeValue(1));
student.setAge(Integer.parseInt(pullParser
.getAttributeValue(2)));
students.add(student);
}
if (tagname.equals("teacher")) {
teacher = new Teacher();
teacher.setId(pullParser.getAttributeValue(0));
teacher.setName(pullParser.getAttributeValue(1));
teacher.setAge(Integer.parseInt(pullParser
.getAttributeValue(2)));
teachers.add(teacher);
}
if (tagname.equals("customer")) {
customer = new Customer();
customer.setId(pullParser.getAttributeValue(0));
customer.setName(pullParser.getAttributeValue(1));
customer.setAge(Integer.parseInt(pullParser
.getAttributeValue(2)));
customers.add(customer);
}
}
eventType = pullParser.next();// 继续解析下一个,不让它死循环下去
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(1);

}

posted @ 2015-12-23 09:02  请叫我码农怪蜀黍  阅读(202)  评论(0编辑  收藏  举报