android解析XML文件的三方法之DOM

    DOM解析XML文件时,会将XML文件的所有内容以文档树方式存放在内存中,然后允许您使用DOM API遍历XML树、检索所需的数据。使用DOM操作XML的代码看起来是比较直观的,并且在某些方面比基于SAX的实现更加简单。但是,因为DOM需要将XML文件的所有内容以文档树方式存放在内存中,所以内存的消耗比较大,特别对于运行Android的移动设备来说,因为设备的资源比较宝贵,所以建议还是采用SAX来解析XML文件,当然,如果XML文件的内容比较小采用DOM也是可行的。

1:person.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>

2:DOMPersonService

package cn.itcast.service;

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.SAXParser;
import javax.xml.parsers.SAXParserFactory;

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

import cn.itcast.domain.Person;
/**
 * 采用DOM解析XML内容
 */
public class DOMPersonService {

	public static List<Person> getPersons(InputStream inStream) throws Throwable{
		List<Person> persons = new ArrayList<Person>();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document documnet = builder.parse(inStream);
		Element root = documnet.getDocumentElement();
		NodeList personNodes = root.getElementsByTagName("person");
		for(int i=0 ; i < personNodes.getLength(); i++){
			Person person = new Person();
			Element personElement = (Element)personNodes.item(i);
			person.setId(new Integer(personElement.getAttribute("id")));
			NodeList personChilds = personElement.getChildNodes();
			for(int y=0 ; y < personChilds.getLength(); y++){
				if(personChilds.item(y).getNodeType()==Node.ELEMENT_NODE){//判断当前节点是否是元素类型节点
					Element childElement = (Element)personChilds.item(y);
					if("name".equals(childElement.getNodeName())){
						person.setName(childElement.getFirstChild().getNodeValue());
					}else if("age".equals(childElement.getNodeName())){
						person.setAge(new Short(childElement.getFirstChild().getNodeValue()));
					}
				}
			}
			persons.add(person);
		}
		return persons;
	}
}

3:测试类

public void testDomGetPersons() throws Throwable{
		InputStream inStream = getClass().getClassLoader().getResourceAsStream("person.xml");
		List<Person> persons = DOMPersonService.getPersons(inStream);
		for(Person person : persons){
			Log.i(TAG, person.toString());
		}
	}

 可参考:http://www.cnblogs.com/zhangdongzi/archive/2011/04/14/2016434.html

相关推荐