Android--xml解析(Dom)


Xml数据原型为:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>李明</name>
<age>30</age>
</person>
<person id="20">
<name>李向梅</name>
<age>25</age>
</person>
</persons>
--------------------------------------------------》


package cn.android.dom;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cn.android.domain.Person;

/**
* dom解析xml实现类
* @author Administrator
*
* 2010-6-29 下午08:16:27
*/
public class DomParser {

/**
* 解析xml文件,返回对象集合
* @param is xml文件的输入流
* @return 对象集合
* @throws Exception
*/
public static List<Person> paseXml(InputStream is) throws Exception {

//新建一个集合,用于存放解析后的对象
List<Person> personList = new ArrayList<Person>();

//创建对象引用
Person person = null;

//得到Dom解析对象工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

//通过工厂创建Dom解析对象实例
DocumentBuilder db = factory.newDocumentBuilder();

//将xml文件的输入流交给Dom解析对象进行解析,并将Dom树返回。
Document document = db.parse(is);

//通过Dom树接收到根元素
Element rootElement = document.getDocumentElement();

//通过根元素获得下属的所有名字为person节点
NodeList nodeList = rootElement.getElementsByTagName("person");

//遍历取出来的person节点集合
for (int i = 0; i < nodeList.getLength(); i++) {

//得到一个person节点
Element personElement = (Element) nodeList.item(i);

//新建一个Person对象
person = new Person();

//将xml标签的Id属性值赋值给Person对象的Id属性
person.setId(new Integer(personElement.getAttribute("id")));

//得到person标签的下属所节点
NodeList personChildList = personElement.getChildNodes();

//循环的到的下属标签
for (int y = 0; y < personChildList.getLength(); y++) {

//创建一个引用,指向循环的标签
Node node = personChildList.item(y);

//如果此循环出来的元素是 Element对象,即标签元素,那么执行以下代码
if (Node.ELEMENT_NODE == node.getNodeType()) {

//如果这个标签的名字是name,那么得到它的值,赋值给Person对象
if("name".equals(node.getNodeName())) {
String nameValue = node.getFirstChild().getNodeValue();
person.setName(nameValue);
}

//如果这个标签的名字是age,那么得到它的值,赋值给Person对象
if("age".equals(node.getNodeName())) {
String ageValue = node.getFirstChild().getNodeValue();
person.setAge(new Short(ageValue));
}
}

}

//将此person对象添加到personList中
personList.add(person);

//将person制空
person = null;

}

//返回xml解析后得到的对象集合
return personList;

}


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值