吾将上下而求索……

博客园 首页 新随笔 联系 订阅 管理

这次把代码整理了一下,打包发上来了,程序中需要用到的jar包也一起打在里面了,有兴趣的朋友可以解压后直接导入的eclipse里运行!

     xml是一种广为使用的可扩展标记语言,java中解析xml的方式有很多,最常用的像jdom、dom4j、sax等等。前两天刚好有个程序需要解析xml,就学了下jdom,写了个小例子,这里做个学习笔记。

     要使用jdom解析xml文件,需要下载jdom的包,我使用的是jdom-1.1。解压之后,将lib文件夹下的.jar文件以及build文件夹下的jdom.jar拷贝到工程文件夹下,然后就可以使用jdom操作xml文件了。

     一、读取xml文件

     假设有这样一个xml文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <sys-config>
 3     <jdbc-info>
 4         <driver-class-name>oracle.jdbc.driver.OracleDriver</driver-class-name>
 5         <url>jdbc:oracle:thin:@localhost:1521:database</url>
 6         <user-name>why</user-name>
 7         <password>why</password>
 8     </jdbc-info>
 9     <provinces-info>
10         <province id="hlj" name="黑龙江">
11             <city id="harb">哈尔滨</city>
12             <city id="nj">嫩江</city>
13         </province>
14         <province id="jl" name="吉林"></province>
15     </provinces-info>
16 </sys-config>

首先,用 org.jdom.input.SAXBuilder 这个类取得要操作的xml文件,会返回一个 org.jdom.Document 对象,这里需要做一下异常处理。然后,取得这个xml文件的根节点,org.jdom.Element 代表xml文件中的一个节点,取得跟节点后,便可以读取xml文件中的信息。利用 org.jdom.xpath.XPath 可以取得xml中的任意制定的节点中的信息。

    例如,要取得上面文件中的 <jdbc-info> 下的 <driver-class-name> 中的内容,先取得这个节点Element driverClassNameElement = (Element)XPath.selectSingleNode(rootEle, "//sys-config/jdbc-info/driver-class-name"),注意,根节点前要使用两个 "/" ,然后,用 driverClassNameElement.getText() 便可以取得这个节点下的信息。

    如果一个节点下有多个名称相同的子节点,可以用XPath.selectNodes()方法取得多个子节点的List,遍历这个List就可以操作各个子节点的内容了。

    下面是我写的读取上面xml文件的例子,比起文字描述更直观一些吧:

 1 package com.why.jdom;
 2 
 3 import java.io.IOException;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 
 7 import org.jdom.input.SAXBuilder;
 8 import org.jdom.xpath.XPath;
 9 import org.jdom.Document;
10 import org.jdom.Element;
11 import org.jdom.JDOMException;
12 
13 public class ReadXML {
14 
15     /**
16      * @param args
17      */
18     public static void main(String[] args) {
19         SAXBuilder sax = new SAXBuilder();
20         try {
21             Document doc = sax.build("src/config.xml");
22             Element rootEle = doc.getRootElement();
23             Element driverClassNameElement = (Element)XPath.selectSingleNode(rootEle, "//sys-config/jdbc-info/driver-class-name");
24             String driverClassName = driverClassNameElement.getText();
25             System.out.println("driverClassName = " + driverClassName);
26             
27             List provinceList = XPath.selectNodes(rootEle, "//sys-config/provinces-info/province");
28             for(Iterator it = provinceList.iterator();it.hasNext();){
29                 Element provinceEle = (Element)it.next();
30                 String proId = provinceEle.getAttributeValue("id");
31                 String proName = provinceEle.getAttributeValue("name");
32 
33                 System.out.println("provinceId = " + proId + "   provinceName = " + proName);
34                 
35                 List cityEleList = (List)provinceEle.getChildren("city");
36                 
37                 for(Iterator cityIt = cityEleList.iterator();cityIt.hasNext();){
38                     Element cityEle = (Element)cityIt.next();
39                     String cityId = cityEle.getAttributeValue("id");
40                     String cityName = cityEle.getText();
41 
42                     System.out.println("    cityId = " + cityId + "   cityName = " + cityName);
43                 }
44             }
45         } catch (JDOMException e) {
46             // TODO 自动生成 catch 块
47             e.printStackTrace();
48         } catch (IOException e) {
49             // TODO 自动生成 catch 块
50             e.printStackTrace();
51         }
52 
53     }
54 
55 }

二、写xml文件

 

    写xml文件与读取xml文件的操作类似,利用 org.jdom.output.XMLOutputter 就可以将处理好的xml输出到文件了。可以设置文件的编码方式,不过一般使用UTF-8就可以了。代码如下:

 1 package com.why.jdom;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 import org.jdom.Document;
 8 import org.jdom.Element;
 9 import org.jdom.output.XMLOutputter;
10 
11 public class WriteXML {
12 
13         
14     /**
15      * @param args
16      */
17     public static void main(String[] args) {
18         // TODO 自动生成方法存根
19         Element rootEle = new Element("sys-config");
20         Element provincesEle = new Element("provinces-info");
21         
22         Element provinceEle = new Element("province");
23         provinceEle.setAttribute("id","hlj");
24         provinceEle.setAttribute("name","黑龙江省");
25         
26         Element cityEle1 = new Element("city");
27         cityEle1.setAttribute("id","harb");
28         cityEle1.addContent("哈尔滨");
29         
30         Element cityEle2 = new Element("city");
31         cityEle2.setAttribute("id","nj");
32         cityEle2.addContent("嫩江");
33         
34         
35         provinceEle.addContent(cityEle1);
36         provinceEle.addContent(cityEle2);
37         provincesEle.addContent(provinceEle);
38         rootEle.addContent(provincesEle);
39         
40         Document doc = new Document(rootEle);
41         
42         XMLOutputter out = new XMLOutputter();
43         
44         
45 //        out.setFormat(Format.getCompactFormat().setEncoding("GBK"));//设置文件编码,默认为UTF-8
46         String xmlStr = out.outputString(doc);
47         System.out.println(xmlStr);
48         
49         try {
50             out.output(doc, new FileOutputStream("c:/test.xml"));
51         } catch (FileNotFoundException e) {
52             // TODO 自动生成 catch 块
53             e.printStackTrace();
54         } catch (IOException e) {
55             // TODO 自动生成 catch 块
56             e.printStackTrace();
57         }
58         
59     }
60 
61 }

TestJdom.rar  转:http://wuhongyu.iteye.com/blog/361842

 

posted on 2013-10-30 22:16  sun&flower  阅读(281)  评论(0编辑  收藏  举报