public class DomXml
{
/**
* 解析后并返回一个对象集合
*
* @param inStream xml输入流
* @return 解析后并返回一个对象集合
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public List<Person> domParser(InputStream inStream) throws ParserConfigurationException, SAXException, IOException
{
List<Person> persons = new ArrayList<Person>();
//创造一个工厂
DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder
DocumentBuilder builder = documentBuilder.newDocumentBuilder();
//创建一个 Dom
Document document = builder.parse(inStream);
//根元素
Element root = document.getDocumentElement();
//获取元素列表
NodeList nodeList = root.getElementsByTagName("person");
for(int i=0; i<nodeList.getLength();i++){
Person person = new Person();
//获取子节点元素周期律
Element personElements = (Element)nodeList.item(i);
person.setId(new Integer(personElements.getAttribute("id")));
//获取子节点
NodeList personChild = personElements.getChildNodes();
for(int j=0; j<personChild.getLength();j++){
//判断是否是元素节点
if(personChild.item(j).getNodeType() == Node.ELEMENT_NODE){
Element child = (Element)personChild.item(j);
//判断是否是name节点
if(child.getNodeName().equals("name")){
person.setName(child.getFirstChild().getNodeValue());
//判断是否是age节点
}else if(child.getNodeName().equals("age")){
person.setAge(new Short(child.getFirstChild().getNodeValue()));
}
}
}
persons.add(person);
}
return persons;
}
}
public void testReadDOM() throws ParserConfigurationException, SAXException, IOException{ DomXml sax = new DomXml(); InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("secn.xml"); List<Person> persons = sax.domParser(inStream); for(Person person:persons){ Log.i("SaxTest", String.valueOf(person.getName())); } }