Android学习笔记(六)

DOM解析XML

 

org.wp.service

DOMPersonService

package org.wp.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 org.wp.domain.Person;

public class DOMPersonService {

	public static List<Person> readXml(InputStream inStream) throws Exception {
		List<Person> persons = new ArrayList<Person>();

		// 得到DOM解析器的工厂实例
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 从DOM工厂获得DOM解析器
		DocumentBuilder builder = factory.newDocumentBuilder();
		// 解析XML文档的输入流,得到一个Document
		Document document = builder.parse(inStream);
		// 得到XML文档的根节点
		Element root = document.getDocumentElement();
		// 得到person的节点列表
		NodeList nodes = root.getElementsByTagName("person");

		for (int i = 0; i < nodes.getLength(); i++) {
			Element personElement = (Element) nodes.item(i);
			Person person = new Person();
			person.setId(new Integer(personElement.getAttribute("id")));
			// 得到节点的子节点
			// Element / Text == Node
			NodeList childNodes = personElement.getChildNodes();

			for (int y = 0; y < childNodes.getLength(); y++) {
				Node childNode = (Node) childNodes.item(y);
				if (childNode.getNodeType() == Node.ELEMENT_NODE) {
					Element childElement = (Element) childNode;
					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;
	}
}

 

 

org.wp.xml

DOMPersonServiceTest

package org.wp.xml;

import java.io.InputStream;
import java.util.List;
import org.wp.domain.Person;
import org.wp.service.DOMPersonService;
import android.test.AndroidTestCase;
import android.util.Log;

public class DOMPersonServiceTest extends AndroidTestCase {

	private static final String TAG = "DOMPersonServiceTest";

	public void testReadXml() throws Exception {
		InputStream inStream = DOMPersonServiceTest.class.getClassLoader()
				.getResourceAsStream("wp.xml");
		List<Person> persons = DOMPersonService.readXml(inStream);
		for (Person person : persons) {
			Log.i(TAG, person.toString());
		}
	}
}

 

 

 

 

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