DOM解析XML

我们在D盘根目录下新建一个xml文件demo_01.xml:

1 <?xml version="1.0" encoding="GBK"?>
2 <addresslist>
3     <name>李兴华</name>
4     <name>张孝祥</name>
5 </addresslist>

然后写一个Java类解析这个xml文件:

 1 import java.io.File;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import javax.xml.parsers.ParserConfigurationException;
 7 
 8 import org.w3c.dom.Document;
 9 import org.w3c.dom.NodeList;
10 import org.xml.sax.SAXException;
11 
12 public class XML_DOM_01 {
13 
14     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
15         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
16         DocumentBuilder builder = factory.newDocumentBuilder();
17         Document doc = builder.parse(new File("D:"+File.separator+"demo_01.xml"));
18         NodeList nl = doc.getElementsByTagName("name");
19         System.out.println("姓名:"+nl.item(1).getFirstChild().getNodeValue());
20     }
21 }

运行程序控制台输出:张孝祥。

我们将要解析的xml文档变得稍微复杂一点demo_02.xml:

 1 <?xml version="1.0" encoding="GBK"?>
 2 <addresslist>
 3     <linkman>
 4         <name>李兴华</name>
 5         <email>lxh@163.com</email>
 6     </linkman>
 7     <linkman>
 8         <name>张孝祥</name>
 9         <email>zxx@163.com</email>
10     </linkman>
11 </addresslist>
 1 import java.io.File;
 2 import java.io.IOException;
 3 
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import javax.xml.parsers.ParserConfigurationException;
 7 
 8 import org.w3c.dom.Document;
 9 import org.w3c.dom.Element;
10 import org.w3c.dom.NodeList;
11 import org.xml.sax.SAXException;
12 
13 public class XML_DOM_02 {
14 
15     public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
16         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
17         DocumentBuilder builder = factory.newDocumentBuilder();
18         Document doc = builder.parse(new File("D:"+File.separator+"demo_02.xml"));
19         NodeList nl = doc.getElementsByTagName("linkman");
20         for(int i=0;i<nl.getLength();i++){
21             Element e = (Element) nl.item(i);
22             System.out.println("姓名:"+e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
23             System.out.println("邮箱:"+e.getElementsByTagName("email").item(0).getFirstChild().getNodeValue());
24         }
25     }
26 }

运行程序控制台输出:

 

posted on 2015-11-09 01:48  confirmCname  阅读(141)  评论(0编辑  收藏  举报

导航