码迷,mamicode.com
首页 > 编程语言 > 详细

Java笔记——XML解析

时间:2015-02-07 21:36:47      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

 1 import java.io.File;
 2 import java.io.IOException;
 3 import javax.xml.parsers.DocumentBuilder;
 4 import javax.xml.parsers.DocumentBuilderFactory;
 5 import javax.xml.parsers.ParserConfigurationException;
 6 import org.w3c.dom.Document;
 7 import org.w3c.dom.Element;
 8 import org.w3c.dom.Node;
 9 import org.w3c.dom.NodeList;
10 import org.xml.sax.SAXException;
11 
12 public class XmlTest {
13 
14     public static void main(String[] args) {
15 
16         try {
17             
18             DocumentBuilderFactory builderFactory = DocumentBuilderFactory
19                     .newInstance();
20             DocumentBuilder builder = builderFactory.newDocumentBuilder();
21             Document document = builder.parse(new File("NewFile.xml"));
22             Element root = document.getDocumentElement();
23             System.out.println(root.getAttribute("name")+":");
24             NodeList list = root.getElementsByTagName("student");
25             for (int i = 0; i < list.getLength(); i++) {
26                 Element student = (Element) list.item(i);
27                 System.out.println("-----------------------");
28                 System.out.println("id= " + student.getAttribute("id"));
29                 NodeList clist = student.getChildNodes();
30                 for (int j = 0; j < clist.getLength(); j++) {
31                     Node c = clist.item(j);
32                     if (c instanceof Element) {
33                         System.out.println(c.getNodeName() + "="
34                                 + c.getTextContent());
35                     }
36                 }
37             }
38 
39         } catch (ParserConfigurationException e) {
40             e.printStackTrace();
41         } catch (SAXException e) {
42             e.printStackTrace();
43         } catch (IOException e) {
44             e.printStackTrace();
45         }
46 
47     }
48 }

被解析的XML:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <root name="StudentInformation">
 3     <student id="1">
 4         <name>张三</name>
 5         <address>北京</address>
 6     </student>
 7     <student id="2">
 8         <name>李四</name>
 9         <address>上海</address>
10     </student>
11     <student id="3">
12         <name>王五</name>
13         <address>广州</address>
14     </student>
15 </root>

 

显示结果:

StudentInformation:
-----------------------
id= 1
name=张三
address=北京
-----------------------
id= 2
name=李四
address=上海
-----------------------
id= 3
name=王五
address=广州

Java笔记——XML解析

标签:

原文地址:http://www.cnblogs.com/shenliangwei/p/4279302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!