本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处!

--Comic Sans MS

Xml解析具有跨平台性,语言无关性,易操作性,因此广受开发者的欢迎。作为安卓开发者,至少有三种解析方式需要理解,Dom、Sax、Pull。

另外Java的四种解析XML的方法:http://developer.51cto.com/art/200903/117512.htm

1、首先讲一下dom解析

解析原理:将xml装入Dom树,依次根据Tag查到每个节点,然后取得结点里的对象属性。

以本地xml解析为例:

book.xml放到项目lib目录下

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="12">
<name>thinking in java</name>
<price>85.5</price>
</book>
<book id="15">
<name>Spring in Action</name>
<price>39.0</price>
</book>
</books>

操作逻辑:

public static void main(String[] args) throws Exception {
InputStream input = new FileInputStream("lib/book.xml");
List<Book> books = getBooks(input);
for (Book book : books) {
System.out.println(book.toString());
}
} public static List<Book> getBooks(InputStream inputStream) throws Exception {
List<Book> list = new ArrayList<Book>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//new一个factory来处理文件
DocumentBuilder builder = factory.newDocumentBuilder();//做一个处理框架
Document document = builder.parse(inputStream);// 把文件形成流的形式,放到一个doucument对象里
Element element = document.getDocumentElement();// 获得其中的元素集
NodeList bookNodes = element.getElementsByTagName("book");// 获得元素集下有一叫book的集合
for (int i = 0; i < bookNodes.getLength(); i++) {
Element bookElement = (Element) bookNodes.item(i);// 获取一个元素,然后设值
Book book = new Book();
book.setId(Integer.valueOf(bookElement.getAttribute("id")));
NodeList childNodes = bookElement.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) {
if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {// 结点
String type=childNodes.item(j).getNodeName();
String value = childNodes.item(j).getFirstChild()
.getNodeValue();
if ("name".equals(type)) {
book.setName(value);
} else if ("price".equals(type)) {
book.setPrice(Float.valueOf(value));
}
}
}// end for j
list.add(book);
}// end for i
return list;
}

2、

其次sax解析也相当常用

解析原理:将xml装入Sax解析工厂中,根据既定的模式可选择解析,使用的是标记事件驱动方式。

BookXmlHandler:

public class BookXMLHandler extends DefaultHandler {

	private List<Book> books;
private Book book;
private String tag; public List<Book> getBooks() {
// TODO Auto-generated method stub
return books;
} /*
* 文档开始时触发
*/
@Override
public void startDocument() throws SAXException {
super.startDocument();
books = new ArrayList<Book>();
} /*
* 元素开始时触发
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
tag = qName;
if ("book".equals(tag)) {
book = new Book();
book.setId(Integer.valueOf(attributes.getValue(0)));
}
} /*
* 读取元素内容
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if (tag == null) {
return;
}
String content = new String(ch, start, length);
if (content.trim().equalsIgnoreCase(null)
|| content.trim().equalsIgnoreCase("")) {
return;
}// 一定要记得trim
if ("name".equals(tag)) {
book.setName(content);
} else if ("price".equals(tag)) {
System.out.println(content);
book.setPrice(Float.valueOf(content));
}
} /*
* 元素结束时触发
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if ("book".equals(qName)) {
books.add(book);
book = null;
tag = null;
}
} /*
* 文档结束时触发
*/
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}

操作逻辑:

	public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputStream input = new FileInputStream("lib/book.xml");
List<Book> books = getBooks(input);
for (Book book : books) {
System.out.println(book.toString());
}
} private static List<Book> getBooks(InputStream input) throws Exception {
// TODO Auto-generated method stub
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
BookXMLHandler handler = new BookXMLHandler();
saxParser.parse(input, handler);
return handler.getBooks();
}

3、

第三种pull解析在安卓中是个特例

解析原理:它比Sax封装又高一个等级,是Sax的浓缩版,测试需要在Android环境下测。

测试逻辑:

public class PullParseTest extends AndroidTestCase {
public void testPull() throws Exception {
InputStream input = getContext().getAssets().open("book.xml");
List<Book> books = getBooks(input);
for (Book book : books) {
Log.i("AthrunTag", book.toString());
}
} public List<Book> getBooks(InputStream inputStream) throws Exception {
List<Book> books = null;
Book book = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(inputStream, "UTF-8");
int event = parser.getEventType();// 产生第一个事件
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_DOCUMENT:// 判断当前事件是否是文档开始事件
books = new ArrayList<Book>();// 初始化books集合
break;
case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
if ("book".equals(parser.getName())) {// 判断开始标签元素是否是book
book = new Book();
book.setId(Integer.parseInt(parser.getAttributeValue(0)));// 得到book标签的属性值,并设置book的id
}
if (book != null) {
if ("name".equals(parser.getName())) {// 判断开始标签元素是否是name
book.setName(parser.nextText());
} else if ("price".equals(parser.getName())) {// 判断开始标签元素是否是price
book.setPrice(Float.parseFloat(parser.nextText()));
}
}
break;
case XmlPullParser.END_TAG:// 判断当前事件是否是标签元素结束事件
if ("book".equals(parser.getName())) {// 判断结束标签元素是否是book
books.add(book);// 将book添加到books集合
book = null;
}
break;
}
event = parser.next();// 进入下一个元素并触发相应事件
}// end while
return books;
}
}

三种解析“真相”只有一个!

12:thinking in java:85.5
15:Spring in Action:39.0

3Q!

Android中级之网络数据解析一之xml解析的更多相关文章

  1. Android中获取网络数据时的分页加载

    //此实在Fragment中实现的,黄色部分为自动加载,红色部分是需要注意的和手动加载,    蓝色部分是睡眠时间,自我感觉不用写  ,还有就是手动加载时,不知道为什么进去后显示的就是最后一行,求大神 ...

  2. IOS 网络浅析-(五 xml解析)

    XML 可扩展标记语言 用于标记电子文件使其具有结构性的标记语言,可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言 易读性高,编码手写难度小,数据量大 NSXMLPars ...

  3. WebService传递XML数据 C#DataSet操作XML 解析WebService返回的XML数据

    Webservice传递的数据只能是序列化的数据,典型的就是xml数据.   /// <summary>         /// 通过用户名和密码 返回下行数据         /// & ...

  4. [Android]天气App 3 网络数据的请求和Json解析

      Android客户端开发,不仅仅是在Android端开发,还需要有相应的后台服务支持,否则的话,客户端的数据就只能放到本地自己做处理.我认为的原生态的App就是对应服务端的Client.他能像浏览 ...

  5. 网络HTTP、JSON、XML解析等 复习

    一.一个HTTP请求的基本要素1.请求URL:客户端通过哪个路径找到服务器 2.请求参数:客户端发送给服务器的数据* 比如登录时需要发送的用户名和密码 3.返回结果:服务器返回给客户端的数据* 一般是 ...

  6. Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  7. Android系列之网络(一)----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4 ...

  8. 网络数据的XML解析

    网络应用中的数据解析,因为最近的应用,无论是Android的和ios平台的,一直用也是建议用的都是Json解析, xml解析都有点被遗忘了. 然后最近自己在做着玩一个ios的小应用,涉及网络数据的抓取 ...

  9. Android系列之网络(二)----HTTP请求头与响应头

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

随机推荐

  1. 硬件相关-ADC原理(未完成)

    一.模数转换的一般步骤: 1)采样和保持 为了把模拟信号转换成对应的数字信号,必须首先将模拟量每隔一定时间抽取一次样值,使时间上连续变化的模拟量变为一个时间上断续变化的模拟量,这个过程称为采样. 为了 ...

  2. python3.4 安装ipython notebook

    1.安装python3.4 2.安装pyreadline 3.安装ipython-1.2.1.zip 4.安装pyzmq-14.7.0-cp34-none-win32.whl,ZIP包有问题,下载wh ...

  3. html表格属性

    一.在表格中插入文字及图片 1.把图片及文字分开到不同的[tr]标签表格内. <html> <body> <table border="1" widt ...

  4. UITableView基本使用和cell的属性

    在ios的UI中UITableView是个常用且强大的控件 基本使用: 1>设置代理,一般把控制器设为代理:self.tableView.delegate = self; 2>遵守代理的协 ...

  5. android开发 drawtext的开始坐标位置

    我们canvas绘制文字的遇到一个不知道drawtext(str,x,y,paint)  中的x.y坐标值怎么定义,,如果设为(0,0)的话文字就不会出来了.因此查找到一下资料: 问:canvas.d ...

  6. 【Longest Palindromic Substring】cpp

    题目: Given a string S, find the longest palindromic substring in S. You may assume that the maximum l ...

  7. 在线自动下载最新版本jquery

    <script src="http://code.jquery.com/jquery-latest.js">

  8. 在ubuntu上搭建reviewboard

    review board 2.0.5 ubuntu ubuntu-12.04.1-desktop-amd64 基本上基于这个教程:http://alephnullplex.appspot.com/bl ...

  9. SPOJ-SQRBR Square Brackets

    原题传送:http://www.spoj.pl/problems/SQRBR 动态规划. 设f[i][j]表示前i个位置在合法情况下缺少j个右括号的方案数. 转移方程为: f[i][j] = f[i- ...

  10. 【CodeForces】【#285】Div.2

    生平第一场Codeforce……纪念一下,虽然跪的跟渣渣似的……啊不就是跪成渣渣了…… A.B暴力过去的……不知道会不会超时……C我犯了个2B错误,让输出总共多少条边,我都求出来边集E了……直接输出E ...