(4)根据节点名称、属性值等信息遍历XML文件,存储起来
public class Person { private Integer id; private String name; private Short age; public Person(){} public Person(Integer id, String name, Short age) { this.id = id; this.name = name; this.age = age; } // 省略setter()和getter()方法 }
public static List<Person> getPersons(InputStream inStream) throws Exception{ List<Person> persons = new ArrayList<Person>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(inStream); Element root = document.getDocumentElement(); NodeList personNodes = root.getElementsByTagName("person"); for(int i=0; i < personNodes.getLength() ; i++){ Element personElement = (Element)personNodes.item(i); int id = new Integer(personElement.getAttribute("id")); Person person = new Person(); person.setId(id); NodeList childNodes = personElement.getChildNodes(); for(int y=0; y < childNodes.getLength() ; y++){ if(childNodes.item(y).getNodeType()==Node.ELEMENT_NODE){ if("name".equals(childNodes.item(y).getNodeName())){ String name = childNodes.item(y).getFirstChild().getNodeValue(); person.setName(name); }else if("age".equals(childNodes.item(y).getNodeName())){ String age = childNodes.item(y).getFirstChild().getNodeValue(); person.setAge(new Short(age)); } } } persons.add(person); } inStream.close(); return persons; }
(2)DOM解析中是一种树形的结构,节点与节点之间都有这等级关系,我们简单的给出一个图示如下:
我们对比看看的xml文件的内容与解析出来的树形结构图:
原文地址:http://blog.csdn.net/ljtyzhr/article/details/40889529