Posted on 2009-06-19 09:16
周競先 閱讀(424)
評論(0) 編輯 收藏 所屬分類:
J2EE 、
xml
根據(jù)上一篇文章構(gòu)造的XML進行簡單的解析,代碼如下:
1 package com.potevio.telecom;
2
3 //文件類
4 import java.io.File;
5
6 //負責解析的類
7 import javax.xml.parsers.DocumentBuilder;
8 import javax.xml.parsers.DocumentBuilderFactory;
9
10 //節(jié)點類
11 import org.w3c.dom.Document;
12 import org.w3c.dom.NodeList;
13
14 /**
15 * @description 解析"北京到長沙的簡單列車時刻表"信息
16 *
17 * @author Zhou-Jingxian
18 *
19 * @date Jun 18, 2009
20 *
21 */
22 public class ParserXML {
23
24 public static void main(String[] args) {
25
26 try{
27 //需要解析的文件
28 File file = new File("北京到長沙火車時刻表.xml");
29
30 //解析器工廠類
31 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
32
33 //解析器
34 DocumentBuilder builder = factory.newDocumentBuilder();
35
36 //操作的Document對象
37 Document document = builder.parse(file);
38
39 //節(jié)點名稱
40 NodeList nodelist = document.getElementsByTagName("車次");
41
42 //解析內(nèi)容
43 for(int i = 0; i<nodelist.getLength(); i++){
44 System.out.println("--------"+(i+1)+"---------");
45 System.out.println("車類別:"+document.getElementsByTagName("車次").item(i).getAttributes().getNamedItem("類別").getNodeValue());
46 System.out.println("車次號:"+document.getElementsByTagName("名字").item(i).getFirstChild().getNodeValue());
47 System.out.println("開車時間:"+document.getElementsByTagName("開車時間").item(i).getFirstChild().getNodeValue());
48
49 }
50 }catch(Exception e){
51 e.printStackTrace();
52
53 }finally{
54
55 }
56 }
57 }
58
運行結(jié)果如下:
Life,simple and happy!