dom4j解析xml文件


一、利用dom4j創建一個內容如下的xml文件SqlMapConfig.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"
 3                        "ibatis-3-config.dtd">
 4 <configuration>
 5    <environments default="development">
 6       <environment id="MySQL">
 7          <transactionManager type="JDBC">123</transactionManager>
 8          <dataSource type="POOLED">
 9              <property name="driver" value="com.mysql.jdbc.Driver"/>
10              <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
11              <property name="username" value="root"/>
12              <property name="password" value="admin"/>
13          </dataSource>
14       </environment>
15    </environments>
16    
17    <mappers>
18       <mapper resource="com/pojo/sql/DepMap.xml"/>
19       <mapper resource="com/pojo/sql/EmpMap.xml"/>
20    </mappers>
21 </configuration>

步驟:
 1.創建一個輸出流,指定創建的SqlMapConfig.xml文件的位置-------OutputStream
    OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
 2.創建一個xml編寫器-------XMLWriter
    XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
    這里os是前面新建的一個輸出流,OutputFormat.createPrettyPrint()是指定輸出的格式的,這里代表內容縮進。
 3.創建xml文檔-------Document、DocumentHelper
    Document document = DocumentHelper.createDocument();
 4.創建里面的所有結點元素-------Elemenet
    Element configuration = document.addElement("configuration");
   ..............
    新建結點元素的形式是:Element 子結點 = 父節點.addElement("子結點名");
    給結點元素添加屬性是:結點.addAttribute("屬性名", "屬性值");
 5.保存xml
    writer.write(document);
代碼如下:

 1 public class CreateXML {
 2 
 3     /**
 4      * @param args
 5      * @throws IOException 
 6      */
 7     public static void main(String[] args) throws IOException {
 8         //創建一個輸出流,指定創建的xml文件的位置
 9         OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
10         
11         XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
12         
13         //創建Document
14         Document document = DocumentHelper.createDocument();
15         
16         Element configuration = document.addElement("configuration");
17         
18         Element environments = configuration.addElement("environments");
19         environments.addAttribute("default", "development");
20         
21         Element environment = environments.addElement("environment");
22         environment.addAttribute("id", "MySQL");
23         Element transactionManager = environment.addElement("transactionManager");
24         transactionManager.addAttribute("type", "JDBC");
25         transactionManager.setText("123");
26         
27         Element dataSource = environment.addElement("dataSource");
28         dataSource.addAttribute("type", "POOLED");
29         Element driver = dataSource.addElement("property");
30         driver.addAttribute("name", "driver");
31         driver.addAttribute("value", "com.mysql.jdbc.Driver");
32         Element url = dataSource.addElement("property");
33         url.addAttribute("name", "url");
34         url.addAttribute("value", "jdbc:mysql://127.0.0.1:3306/test");
35         Element username = dataSource.addElement("property");
36         username.addAttribute("name", "username");
37         username.addAttribute("value", "root");
38         Element password = dataSource.addElement("property");
39         password.addAttribute("name", "password");
40         password.addAttribute("value", "admin");
41         
42         Element mappers = configuration.addElement("mappers");
43         Element mapper1 = mappers.addElement("mapper");
44         mapper1.addAttribute("resource", "com/pojo/sql/DepMap.xml");
45         Element mapper2 = mappers.addElement("mapper");
46         mapper2.addAttribute("resource", "com/pojo/sql/EmpMap.xml");
47         //保存xml
48         writer.write(document);
49         writer.close();
50     }
51 }

二、查找xml文件的內容
    查找xml文件內容有兩種情況,第一種就是查找出所有同名的結點元素然后遍歷、第二種就是直接找到某個結點元素
    比如遍歷SqlMapConfig.xml,將driver、url、username、password的值讀取出來就有兩種方法,代碼如下
方法一:

 1 public class GetNodes {
 2 
 3     /**方法一:
 4      * 遍歷新建的xml,將driver、url、username、password的值讀取出來
 5      * @param args
 6      * @throws IOException 
 7      * @throws DocumentException 
 8      */
 9     public static void main(String[] args) throws IOException, DocumentException {
10         SAXReader reader = new SAXReader();
11         Document document = reader.read("d:/SqlMapConfig.xml");
12         List<Element> elements = document.selectNodes("/configuration/environments/environment/dataSource/property");
13         String driver = "";
14         String url = "";
15         String username = "";
16         String password = "";
17         for (Element e : elements) {
18             String name = e.attributeValue("name");
19             String value = e.attributeValue("value");
20             if("driver".equals(name)){
21                 driver = value;
22             }else if("url".equals(name)){
23                 url = value;
24             }else if("username".equals(name)){
25                 username = value;
26             }else if("password".equals(name)){
27                 password = value;
28             }
29         }
30         System.out.println("driver:"+driver+",url:"+url+",username:"+username+",password:"+password);
31     }
32 }

  這里List<Element> elements = document.selectNodes("/configuration/environments/environment/dataSource/property")是指將名為property的結點元素全部找出來,用一個List接收。
方法二:

 1 public class GetNodes1 {
 2 
 3     /**方法二:
 4      * 將driver、url、username、password的值讀取出來
 5      * @param args
 6      * @throws IOException 
 7      * @throws DocumentException 
 8      */
 9     public static void main(String[] args) throws IOException, DocumentException {
10         SAXReader reader = new SAXReader();
11         Document document = reader.read("d:/SqlMapConfig.xml");
12         Element driverElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='driver']");
13         Element urlElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='url']");
14         Element usernameElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='username']");
15         Element passwordElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
16         String driver = driverElement.attributeValue("value");
17         String url = urlElement.attributeValue("value");
18         String username = usernameElement.attributeValue("value");
19         String password = passwordElement.attributeValue("value");
20         
21         System.out.println("driver:"+driver+",url:"+url+",username:"+username+",password:"+password);
22     }
23 }

  這種方法就沒有遍歷了,就是直接將要查找的結點找出來,用selectSingleNode()函數。這里的[@name='driver']是指名找到哪一個property結點,相當於一個鍵值對,表示找有name="driver"屬性的property結點。
形式為[@屬性名='屬性值']。

三、修改XML文件
    步驟:
    1.讀取要修改的xml文件
    2.查找到要修改的結點
    3.保存
代碼如下:

 1 public class UpdateNode {
 2 
 3     /**
 4      * 修改密碼為123456
 5      * @param args
 6      * @throws DocumentException 
 7      * @throws IOException 
 8      */
 9     public static void main(String[] args) throws DocumentException, IOException {
10         //讀取並修改
11         SAXReader reader = new SAXReader();
12         Document document = reader.read("d:/SqlMapConfig.xml");
13         Element passwordElement = (Element)document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
14         passwordElement.addAttribute("value", "123456");
15         //保存
16         OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
17         XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
18         writer.write(document);
19         writer.close();
20         os.close();
21     }
22 
23 }

四、刪除XML文件的某個結點元素
  刪除和修改一樣,也是要先找到要刪除的結點,然后刪除之,最后保存修改過的文件。刪除結點的形式為:父節點.remove(子節點);
代碼如下:

 1 public class DeleteNode {
 2 
 3     /**
 4      * 刪除密碼結點
 5      * @param args
 6      * @throws DocumentException 
 7      * @throws IOException 
 8      */
 9     public static void main(String[] args) throws DocumentException, IOException {
10         //找到結點並刪除
11         SAXReader reader = new SAXReader();
12         Document document = reader.read("d:/SqlMapConfig.xml");
13         Element passwordElement = (Element) document.selectSingleNode("/configuration/environments/environment/dataSource/property[@name='password']");
14         passwordElement.getParent().remove(passwordElement);
15         
16         //保存
17         OutputStream os = new FileOutputStream("d:/SqlMapConfig.xml");
18         XMLWriter writer = new XMLWriter(os,OutputFormat.createPrettyPrint());
19         writer.write(document);
20         writer.close();
21         os.close();
22     }
23 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM