创建Activity -----DataActivity 无任何信息
创建bdqn.xml----直接复制进来
创建Javabean----person
private Integer id;
private String name;
private Short age;
创建服务器---DomPersonService com.bdqn.service
public class DomPersonService {
public static List readXml(InputStream inStream) throws Exception {
List persons = new ArrayList();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// 把解析的内容放入到内存中,比较消耗资源
Document document = builder.parse(inStream);
// 获取根元素
Element root = document.getDocumentElement();
// 得到元素列表
NodeList nodes = root.getElementsByTagName("person");
for (int i = 0; i
// 获取每个节点
Element personElement = (Element) nodes.item(i);
Person person = new Person();
// 获取id
person.setId(new Integer(personElement.getAttribute("id")));
// 获取子节点
NodeList childNodes = personElement.getChildNodes();
// 循环找出每个子节点
for (int y = 0; y
Node childNode = (Node) childNodes.item(y);
// 判断节点的类型
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) childNode;
// 获取name子节点取得节点名称来判断
if ("name".equals(childElement.getNodeName())) {
// 存到dto中
person.setName(childElement.getFirstChild()
.getNodeValue());
}
// 获取age子节点 取得节点名称来判断
else if ("age".equals(childElement.getNodeName())) {
person.setAge(new Short(childElement.getFirstChild()
.getNodeValue()));
}
}
}
// 增加到根节点
persons.add(person);
}
return persons;
}
}
创建测试类--XmlPersonServiceTest com.bdqn.test
//单元测试
public class XmlPersonServiceTest extends AndroidTestCase{
private static final String TAG = "XmlPersonServiceTest";
//DOM解析XML
public void testReadXml() throws Exception {
InputStream inStream = XmlPersonServiceTest.class.getClassLoader().getResourceAsStream("bdqn.xml");
List persons = DomPersonService.readXml(inStream);
for (Person person : persons) {
Log.i(TAG,person.toString());
}
}
}