Android读取XML文件(DOM)

 

package com.xiva.service;

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

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

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


import com.xiva.domain.Person;

/**
 * @decription 适合解析小存储的xml文件
 * @author XIVA
 *
 */
public class DOMService {
	
	public static List<Person> readXML(InputStream is) throws Exception
	{
		List<Person> personList = new ArrayList<Person>();
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dombuilder        = domFactory.newDocumentBuilder();
		Document document = dombuilder.parse(is);
		Element root      = document.getDocumentElement();
		NodeList nodes    = root.getElementsByTagName("person");
		
		for(int i=0;i<nodes.getLength();i++){
			
			Element element = (Element) nodes.item(i);
			Person person = new Person();
			person.setId(new Integer(element.getAttribute("id")));
			NodeList childNodes = element.getChildNodes();
			for(int j=0;j<childNodes.getLength();j++){
				
				Node childNode = (Node) childNodes.item(j);
				if(childNode.getNodeType() == Element.ELEMENT_NODE)
				{
					Element childElement = (Element) childNode;
					childElement.getLocalName();
					childElement.getNodeName();
					childElement.getNodeValue();
					childElement.getTagName();
					if("age".equals(childElement.getTagName()))
					{
						person.setAge(childElement.getFirstChild().getNodeValue());
					}else if("name".equals(childElement.getTagName())){
						person.setPersonName(childElement.getFirstChild().getNodeValue());
					}
				}
			}
			personList.add(person);
		}
		
		return personList;
	}
}

 完整代码见附件,DOM与SAX解析的区别在于SAX解析需要一个handler,并触发handler里面的所有事件;而DOM的解析主要需要分析NodeList里面所含值!

 

你可能感兴趣的:(xml,android,J#)