在XML解析和使用原始XML资源中都涉及过对XML的解析,之前使用的是 DOM4J和 XmlResourceParser 来解析的。本文中将使用XmlPullParser来解析,分别解析不同复杂度的test1.xml、test2.xml、test3.xml。代码如下:

MainActivity:

package com.home.xmlparsetest;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.xmlpull.v1.XmlPullParser; import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView; public class MainActivity extends Activity implements OnClickListener {
private Button parseBtn1;
private Button parseBtn2;
private Button parseBtn3;
private ExpandableListView listView; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initWidget();
} private void initWidget() {
parseBtn1 = (Button) findViewById(R.id.main_btn_test1);
parseBtn1.setOnClickListener(this);
parseBtn2 = (Button) findViewById(R.id.main_btn_test2);
parseBtn2.setOnClickListener(this);
parseBtn3 = (Button) findViewById(R.id.main_btn_test3);
parseBtn3.setOnClickListener(this);
listView = (ExpandableListView) findViewById(R.id.list);
} @Override
public void onClick(View v) {
if (v == parseBtn1) {
InputStream is = getAssetsStream("test1.xml");
List<ClassBean> list = parseFile1(is);
listView.setAdapter(new MyAdapter(this, list));
} else if (v == parseBtn2) {
InputStream is = getAssetsStream("test2.xml");
List<ClassBean> list = parseFile2(is);
listView.setAdapter(new MyAdapter(this, list));
} else if (v == parseBtn3) {
InputStream is = getAssetsStream("test3.xml");
List<ClassBean> list = parseFile3(is);
listView.setAdapter(new MyAdapter(this, list));
}
} /**
* 得到Assets里面相应的文件流
*
* @param fileName
* @return
*/
private InputStream getAssetsStream(String fileName) {
InputStream is = null;
try {
is = getAssets().open(fileName);
} catch (IOException e) {
e.printStackTrace();
}
return is;
} /**
* 解析test1.xml
*
* @param is
* @return list
*/
private List<ClassBean> parseFile1(InputStream is) {
List<ClassBean> list = new ArrayList<ClassBean>();
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if ("class".equals(parser.getName())) {
ClassBean bean = new ClassBean();
bean.setId(parser.getAttributeValue(0));
bean.setName(parser.nextText());
list.add(bean);
}
break;
}
event = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
} /**
* 解析test2.xml
*
* @param is
* @return list
*/
private List<ClassBean> parseFile2(InputStream is) {
List<ClassBean> list = null;
ClassBean bean = null;
List<StudentBean> sList = null;
StudentBean be = null;
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<ClassBean>();
break;
case XmlPullParser.START_TAG:
if ("class".equals(parser.getName())) {
bean = new ClassBean();
bean.setId(parser.getAttributeValue(0));
bean.setName(parser.getAttributeValue(1));
sList = new ArrayList<StudentBean>();
} else if ("student".equals(parser.getName())) {
be = new StudentBean();
be.setId(parser.getAttributeValue(0));
be.setName(parser.nextText());
sList.add(be);
}
break;
case XmlPullParser.END_TAG:
if ("class".equals(parser.getName())) {
bean.setList(sList);
list.add(bean);
bean = null;
}
break;
}
event = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
} /**
* 解析test3.xml
*
* @param is
* @return list
*/
private List<ClassBean> parseFile3(InputStream is) {
List<ClassBean> list = null;
ClassBean bean = null;
List<StudentBean> sList = null;
StudentBean be = null;
try {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:
list = new ArrayList<ClassBean>();
break;
case XmlPullParser.START_TAG:
if ("class".equals(parser.getName())) {
bean = new ClassBean();
bean.setId(parser.getAttributeValue(0));
bean.setName(parser.getAttributeValue(1));
sList = new ArrayList<StudentBean>();
} else if ("student".equals(parser.getName())) {
be = new StudentBean();
be.setId(parser.getAttributeValue(0));
sList.add(be);
} else if ("name".equals(parser.getName())) {
be.setName(parser.nextText());
} else if ("sex".equals(parser.getName())) {
be.setSex(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("class".equals(parser.getName())) {
bean.setList(sList);
list.add(bean);
bean = null;
}
break;
}
event = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}

MyAdapter:

package com.home.xmlparsetest;

import java.util.List;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.LinearLayout;
import android.widget.TextView; public class MyAdapter extends BaseExpandableListAdapter {
private List<ClassBean> classList;
private Context context; public MyAdapter(Context context, List<ClassBean> classList) {
this.context = context;
this.classList = classList;
} @Override
public Object getChild(int groupPosition, int childPosition) {
List<StudentBean> sList = classList.get(groupPosition).getList();
StudentBean be = null;
if (sList != null) {
be = sList.get(childPosition);
}
return be;
} @Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
} @Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
List<StudentBean> sList = classList.get(groupPosition).getList(); if (sList != null && sList.size() > 0
&& sList.get(childPosition).getId() != null) {
TextView tv1 = getTextView2();
tv1.setText(sList.get(childPosition).getId());
ll.addView(tv1);
} if (sList != null && sList.size() > 0
&& sList.get(childPosition).getName() != null) {
TextView tv2 = getTextView2();
tv2.setText(sList.get(childPosition).getName());
ll.addView(tv2);
} if (sList != null && sList.size() > 0
&& sList.get(childPosition).getSex() != null) {
TextView tv3 = getTextView2();
tv3.setText(sList.get(childPosition).getSex());
ll.addView(tv3);
}
return ll;
} @Override
public int getChildrenCount(int groupPosition) {
int size = 0;
List<StudentBean> sList = classList.get(groupPosition).getList();
if (sList != null) {
size = sList.size();
}
return size;
} @Override
public Object getGroup(int groupPosition) {
return classList.get(groupPosition);
} @Override
public int getGroupCount() {
return classList.size();
} @Override
public long getGroupId(int groupPosition) {
return groupPosition;
} @Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
TextView tv1 = getTextView1();
tv1.setText(classList.get(groupPosition).getId());
ll.addView(tv1); TextView tv2 = getTextView1();
tv2.setText(classList.get(groupPosition).getName());
ll.addView(tv2);
return ll;
} @Override
public boolean hasStableIds() {
return true;
} @Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
} private TextView getTextView1() {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 20, 0);
TextView tv = new TextView(context);
tv.setLayoutParams(lp);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setPadding(36, 0, 0, 0);
tv.setTextSize(25);
return tv;
} private TextView getTextView2() {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
lp.setMargins(20, 0, 50, 0);
TextView tv = new TextView(context);
tv.setLayoutParams(lp);
tv.setGravity(Gravity.CENTER_VERTICAL);
tv.setPadding(36, 0, 0, 0);
tv.setTextSize(18);
return tv;
}
}

ClassBean实体类:

package com.home.xmlparsetest;

import java.util.List;

public class ClassBean {
private String id;
private String name;
private List<StudentBean> list; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public List<StudentBean> getList() {
return list;
} public void setList(List<StudentBean> list) {
this.list = list;
} }

StudentBean:

package com.home.xmlparsetest;

public class StudentBean {
private String id;
private String name;
private String sex; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} }

布局文件main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" > <Button
android:id="@+id/main_btn_test1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="解析test1" /> <Button
android:id="@+id/main_btn_test2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="解析test2" /> <Button
android:id="@+id/main_btn_test3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="解析test3" />
</LinearLayout> <ExpandableListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ExpandableListView> </LinearLayout>

assets里面的test1.xml:

<?xml version="1.0" encoding="utf-8"?>
<classList> <class id="1">一班</class> <class id="2">二班</class> <class id="3">三班</class> <class id="4">四班</class> </classList>

assets里面的test2.xml:

<?xml version="1.0" encoding="utf-8"?>
<classList> <class id="1" name="一班" >
<student id="1" >张三 </student>
<student id="2" >李四 </student>
</class> <class id="2" name="二班" >
<student id="3" >王五</student>
<student id="4" >赵六</student>
</class> <class id="3" name="三班" >
<student id="5" >小明</student>
<student id="6" >小高 </student>
</class> <class id="4" name="四班" >
<student id="7" >小花</student>
<student id="8" >小红 </student>
</class> </classList>

assets里面的test3.xml:

<?xml version="1.0" encoding="utf-8"?>
<classList> <class id="1" name="一班" >
<student id="1" >
<name>张三</name>
<sex>男</sex>
</student>
<student id="2" >
<name>李四</name>
<sex>男</sex>
</student>
</class> <class id="2" name="二班" >
<student id="3" >
<name>王五</name>
<sex>男</sex>
</student>
<student id="4" >
<name>赵六</name>
<sex>男</sex>
</student>
</class> <class id="3" name="三班" >
<student id="5" >
<name>小明</name>
<sex>男</sex>
</student>
<student id="6" >
<name>小高</name>
<sex>男</sex>
</student>
</class> <class id="4" name="四班" >
<student id="7" >
<name>小花</name>
<sex>女</sex>
</student>
<student id="8" >
<name>小红</name>
<sex>女</sex>
</student>
</class> </classList>

http://www.tuicool.com/articles/EZrqEb

android 中解析XML的方法(转)的更多相关文章

  1. Android中解析XML的方法

    假设我要解析如下的XML文件: <?xml version="1.0" encoding="UTF-8"?> <books> <b ...

  2. Android中解析XML格式数据的方法

    XML介绍:Extensible Markup Language,即可扩展标记语言 一.概述 Android中解析XML格式数据大致有三种方法: SAX DOM PULL 二.详解 2.1 SAX S ...

  3. [置顶] Android学习系列-Android中解析xml(7)

    Android学习系列-Android中解析xml(7) 一,概述 1,一个是DOM,它是生成一个树,有了树以后你搜索.查找都可以做. 2,另一种是基于流的,就是解析器从头到尾解析一遍xml文件.   ...

  4. Android中解析XML

    XML在各种开发中都广泛应用,Android也不例外.作为承载数据的一个重要角色,如何读写XML成为Android开发中一项重要的技能.今天就由我向大家介绍一下在Android平台下几种常见的XML解 ...

  5. android中解析文件的三种方式

    android中解析文件的三种方式     好久没有动手写点东西了,最近在研究android的相关技术,现在就android中解析文件的三种方式做以下总结.其主要有:SAX(Simple API fo ...

  6. Android DOM解析XML方法及优化

    在Android应用开发中,我们常常要在应用启动后从服务器下载一些配置文件,这些配置文件包含一些项目中可能用到的资源,这些文件很多情况下是XML文件,这时就要将XML下载到文件中保存,之后再解析XML ...

  7. 用 ElementTree 在 Python 中解析 XML

    用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...

  8. 【转】Android中JNI的使用方法

    Android中JNI的使用方法 首先看一下Android平台的框架图:(网上盗用) 可以看到Android上层的Application和ApplicationFramework都是使用Java编写, ...

  9. 修改Android中strings.xml文件, 动态改变数据

    有些朋友可能会动态的修改Android中strings.xml文件中的值,在这里给大家推荐一种简单的方法.strings.xml中节点是支持占位符的,如下所示: <string name=&qu ...

随机推荐

  1. swift-基础部分

    变量常量,注释,分号,整数,浮点数.数值行类型转换,类型别名,波尔值,元组,可选,断言              let binaryInteger = 0b10001  let twoThousan ...

  2. x64的调用约定

    在设计调用约定时,x64 体系结构利用机会清除了现有 Win32 调用约定(如 __stdcall.__cdecl.__fastcall._thiscall 等)的混乱.在 Win64 中,只有一个本 ...

  3. 经典SQL查询语句大全

    一.基础1.说明:创建数据库CREATE DATABASE database-name2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备份数 ...

  4. Spark源码分析环境搭建

    原创文章,转载请注明: 转载自http://www.cnblogs.com/tovin/p/3868718.html 本文主要分享一下如何构建Spark源码分析环境.以前主要使用eclipse来阅读源 ...

  5. iOS开发--泛型

    一. 泛型函数 1.单一占位符泛型函数 下面就使用一个经典案例:两个数值进行交换.来使用泛型,写一个通用的函数,这个函数的功能就是交换两个变量的值.在Swift中不允许类型隐式转换,也就是说,如果你定 ...

  6. Struts2笔记——与ServletAPI解耦

    与ServletAPI解耦的访问方式 为了避免与 Servlet API 耦合在一起, 方便 Action 做单元测试, Struts2 对 HttpServletRequest, HttpSessi ...

  7. 277. Find the Celebrity

    题目: Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exi ...

  8. swift:入门知识之函数与闭包

    1.swift中使用关键字func来声明和定义一个函数.调用函数使用它的名字加上小括号中的参数列表. 2.swift使用->方向符号分隔参数的名字和返回值类型 3.swift使用元组(tuple ...

  9. Linux命令-cut

    cut命令用于通过列来提取文本字符 格式:cut [参数] 文本 将/etc/paswd文件以:分割(-d:),获取第七列的内容(-f1) [root@localhost test]# cut -d: ...

  10. Android 怎么使用Bitmap+Canvas 自适应屏幕

    我们可以使用Matrix 来放缩我们得到的Bitmap 从而使我们的BItmap适应我们的手机屏幕 首先我们得先获取我们的手机屏幕的大小 WindowManager wm = (WindowManag ...