Java中Dom解析XML(一)

2014-11-24 07:14:35 · 作者: · 浏览: 0
Java代码:
1 package com.test;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.List;
6 import javax.xml.parsers.DocumentBuilder;
7 import javax.xml.parsers.DocumentBuilderFactory;
8 import org.w3c.dom.Document;
9 import org.w3c.dom.Element;
10 import org.w3c.dom.Node;
11 import org.w3c.dom.NodeList;
12
13 public class DomXML {
14
15 public static void main(String[] args) {
16 try {
17 File file = new File("e:/People.xml");
18 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
19 DocumentBuilder builder = factory.newDocumentBuilder();
20 Document document = builder.parse(file);
21 Element element = document.getDocumentElement();
22
23 List peopleList = new ArrayList();
24 NodeList peopleNodes = element.getElementsByTagName("People");
25 for(int i=0;i
26 People people = new People();
27 Element peopleElement = (Element) peopleNodes.item(i);
28 people.setId(peopleElement.getAttribute("id"));
29 NodeList childPeopleNodes = peopleElement.getChildNodes();
30 for(int j=0;j
31 //DOM解析时候注意子节点前面的空格也会被解析
32 if(childPeopleNodes.item(j) instanceof Element){
33 Element childPeopleElement = (Element) childPeopleNodes.item(j);
34 if(childPeopleElement.getNodeType()==Node.ELEMENT_NODE){
35 if(childPeopleElement.getNodeName().equals("Name")){
36 people.setEnglishName(childPeopleElement.getAttribute("en"));
37 people.setName(childPeopleElement.getTextContent());
38 }
39 else if(childPeopleElement.getNodeName().equals("Age")){
40 people.setAge(childPeopleElement.getTextContent());
41 }
42 }
43 }
44 }
45 peopleList.add(people);
46 }
47
48 for(People people : peopleList){
49 System.out.println(people.getId()+"\t"+people.getName()+"\t"+people.getEnglishName()+"\t"+people.getAge());
50 }
51
52 } catch (Exception e) {
53 // TODO 自动生成的 catch 块
54 e.printStackTrace();
55 }
56
57
58 }
People对象:
1 package com.test;
2
3 public class People {
4 private String id;
5 private String name;
6 private String englishName;
7 private String age;
8 public String getId() {
9 return id;
10 }
11 public void setId(String id) {
12 this.id = id;
13 }
14 public String getName() {
15 return name;
16 }
17 public void setName(String name) {
18 this.name = name;
19 }
20 public String getEnglishName() {
21 return englishName;
22 }
23 public void setEnglishName(String englishName) {
24 this.englishName = englishName;
25 }
26 public String getAge() {
27 return age;
28 }
29 public void setAge(String age) {
30 this.age = age;
31 }
32
xml:
1 < xml version="1.0" encoding="UTF-8" >
2
3
4 张三
5 20
6
7