创建DOMPersonService类
public class DOMPersonService {
public static List<Person> getPersonList(InputStream inStream) throws Exception{
List<Person> personList = new ArrayList();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inStream);
//注意,此时xml文件已经都被装入内存中的document对象里了
//取得根结点(元素节点)
Element root = document.getDocumentElement();
NodeList nodes = root.getElementsByTagName("person");
for(int i=0; i<nodes.getLength(); i++){
Element personElement = (Element) nodes.item(i);
Person person = new Person();
//为person添加id属性值
person.setId(Integer.valueOf(personElement.getAttribute("id")));
NodeList childNodes = personElement.getChildNodes();
//遍历孩子节点,忽略文本节点,保留并处理元素节点
for(int j=0; j<childNodes.getLength(); j++){
Node childNode = childNodes.item(j);
if(childNode.getNodeType() == Node.ELEMENT_NODE){
if("name".equals(childNode.getNodeName() )){
person.setName(childNode.getFirstChild().getNodeValue());
}else if("age".equals(childNode.getNodeName())){
Text textNode = (Text) childNode.getFirstChild();
String ageStr = textNode.getNodeValue();
person.setAge(Integer.valueOf(ageStr));
}
}
}
personList.add(person);
}
return personList;
}
测试方法
public void testDOM() throws Throwable {
List<Person> personList = null;
InputStream inStream = this.getClass().getClassLoader()
.getResourceAsStream("person_list.xml");
personList = DOMPersonService.getPersonList(inStream);
Log.i("TAG", personList.toString());
}