每天进步一点点~~~~~~~~ww.blog.chinaunix.net
superior_2008
全部博文(322)
2013年(5)
2012年(66)
2011年(87)
2010年(164)
小雅贝贝
wylhisto
split_tw
zyhualov
jcodeer
Unixtom9
wang2kk
格伯纳
Phyllis6
浪花小雨
tejorge
imliuqun
15107126
iOSrever
XPhenix
lstfyt
分类: Java
2010-12-31 11:19:38
org.wp.service
DOMPersonService
Java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
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.
DOMPersonServiceTest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
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()); } } }
上一篇:Android学习笔记(五)
下一篇:Android学习笔记(七)
chinaunix网友2011-01-03 15:00:33
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com
登录 注册