• 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 }
  • 相关阅读:
    中文词频统计
    【大数据应用期末总评】Hadoop综合大作业
    【大数据作业十一】分布式并行计算MapReduce
    【大数据作业十】分布式文件系统HDFS 练习
    【大数据作业九】安装关系型数据库MySQL 安装大数据处理框架Hadoop
    【爬虫综合大作业】腾讯视频——大家到底都在看什么?!
    【大数据作业七】爬取全部的校园新闻
    【大数据作业六】获取一篇新闻的全部信息
    【大数据作业五】理解爬虫原理
    【大数据作业四】中文词频统计
  • 原文地址:https://www.cnblogs.com/liuling/p/dom4jxml.html
Copyright © 2020-2023  润新知