DOM解析xml

public class DOMXMLTools {

	public static List<Person> parseXML(InputStream inputStream)throws Exception{
		List<Person> list=new ArrayList<Person>();
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		DocumentBuilder builder=factory.newDocumentBuilder();
		Document document=builder.parse(inputStream);
		Element element=document.getDocumentElement();
		NodeList nodes=element.getElementsByTagName("person");
		for(int i=0;i<nodes.getLength();i++){
			Element pelement=(Element) nodes.item(i);
		    Person person=new Person();
		    person.setId(Integer.parseInt(pelement.getAttribute("id")));
			NodeList nodeList=pelement.getChildNodes();
			for(int j=0;j<nodeList.getLength();j++){
				if(nodeList.item(j).getNodeType()==Node.ELEMENT_NODE){
					if("name".equals(nodeList.item(j).getNodeName())){
						person.setName(nodeList.item(j).getFirstChild().getNodeValue());
					}else if("age".equals(nodeList.item(j).getNodeName())){
						person.setAge(Short.parseShort(nodeList.item(j).getFirstChild().getNodeValue()));
					}
				}
			}
			
			list.add(person);
		}
		
		
		return list;
		
	}
}


你可能感兴趣的:(DOM解析xml)