zoukankan      html  css  js  c++  java
  • java学习:使用dom4j读写xml文件

    dom4j是一个优秀的开源项目,专用于xml文件的读写,而且支持强大的xpath.

    下面的代码演示了对xml文件demo.xml的读写

    demo.xml内容:

     1 <?xml version="1.0" encoding="UTF-8" ?>
     2 <address-list>
     3   <card name="yangjm" id="1">
     4     <sex></sex>
     5     <address><![CDATA[中国上海外滩No.01]]>    </address>
     6     <telephone>13916732212</telephone>
     7   </card>
     8   <card name="zhangsan" id="2">
     9     <sex></sex>
    10     <address>
    11       <item type="家庭地址"><![CDATA[中国.北京.东直门外大街]]>      </item>
    12       <item type="单位地址"><![CDATA[中国.上海.田林路888号]]>      </item>
    13     </address>
    14     <telephone>010-123123</telephone>
    15   </card>
    16 </address-list>
    demo.xml

    java代码:

     1 package jmyang.dom4j;
     2 
     3 /**
     4  * <p>Title:dom4j测试 </p>
     5  * <p>Description: 使用xpath读取节点内容、属性</p>
     6  * <p>Copyright: Copyright (c) 2012</p>
     7  * <p>Company: infosky.com.cn</p>
     8  * @author:yjmyzz@126.com 菩提树下的杨过
     9  * @version 1.0
    10  */
    11 
    12 import java.util.*;
    13 import java.io.*;
    14 import org.dom4j.*;
    15 import org.dom4j.io.*;
    16 
    17 
    18 public class XmlTest {
    19 
    20 
    21     public static void Test() {
    22         String fileName = System.getProperty("user.dir") + "\\demo.xml"; //当前路径下的demo.xml
    23 
    24         try {
    25             SAXReader reader = new SAXReader();
    26             Document doc = reader.read(fileName); //加载xml文件
    27 
    28             List peoples = doc.selectNodes("//*[@name]"); //选择所有具有name属性的节点(即demo.xml中的所有card节点)
    29             for (Iterator iter = peoples.iterator(); iter.hasNext(); ) {
    30                 Element card = (Element) iter.next();
    31                 //System.out.println(node.asXML());
    32                 //System.out.println("---------------------------------------");
    33                 //System.out.println(node.attributeCount());
    34                 List attrList = card.attributes();
    35                 //输出每个card的所有属性
    36                 for (Iterator attr = attrList.iterator(); attr.hasNext(); ) {
    37                     Attribute a = (Attribute) attr.next();
    38                     System.out.println(a.getName() + "=" + a.getValue());
    39 
    40                 }
    41                 System.out.println(
    42                         "----------------------------------------------------");
    43             }
    44 
    45             Element zhangsan = (Element) doc.selectSingleNode("//card[@id='2']"); //查找“id属性”=2的card元素
    46             System.out.println("张三的名称:" + zhangsan.attribute("name").getValue()); //输出zhangsan的name属性
    47 
    48             Node addrFamily = zhangsan.selectSingleNode("./address/item[2]"); //选择zhangsan元素下的address节点下的第2个item子节点
    49             System.out.println("张三的单位地址:" + addrFamily.getStringValue()); //输出cdata内容
    50 
    51             System.out.println(
    52                     "----------------------------------------------------");
    53             //为zhangsan下增加二个节点
    54             zhangsan.addElement("email").addAttribute("type",
    55                     "工作").addText("work@some-domain.com");
    56             zhangsan.addElement("email").addAttribute("type",
    57                     "私人").addCDATA("private@some-domain.com"); //设置CDATA内容
    58 
    59             System.out.println(zhangsan.asXML()); //打印zhangsan节点的xml内容(调试用)
    60             System.out.println(
    61                     "----------------------------------------------------");
    62 
    63             //将上述改动保存到文件demo2.xml
    64             FileWriter fileWriter = new FileWriter(System.getProperty(
    65                     "user.dir") + "\\demo2.xml");
    66 
    67             OutputFormat format = OutputFormat.createPrettyPrint(); //设置美观的缩进格式,便于阅读
    68             //format = OutputFormat.createCompactFormat();//设置紧凑格式(消除多余空格),便于下载
    69             XMLWriter writer = new XMLWriter(System.out, format);
    70             writer.setWriter(fileWriter);
    71             writer.write(doc);
    72             writer.close();
    73 
    74         } catch (Exception e) {
    75             e.printStackTrace();
    76         }
    77 
    78     }
    79 }
    XmlTest.java

    运行结果:

    name=yangjm
    id=1
    ----------------------------------------------------
    name=zhangsan
    id=2
    ----------------------------------------------------
    张三的名称:zhangsan
    张三的单位地址:中国.上海.田林路888号     
    ----------------------------------------------------
    <card name="zhangsan" id="2">
        <sex>女</sex>
        <address>
          <item type="家庭地址"><![CDATA[中国.北京.东直门外大街]]>      </item>
          <item type="单位地址"><![CDATA[中国.上海.田林路888号]]>      </item>
        </address>
        <telephone>010-123123</telephone>
      <email type="工作">work@some-domain.com</email><email type="私人"><![CDATA[private@some-domain.com]]></email></card>
    ----------------------------------------------------

    保存后的demo2.xml

    <?xml version="1.0" encoding="UTF-8"?>

    <address-list>
      <card name="yangjm" id="1">
        <sex>男</sex> 
        <address><![CDATA[中国上海外滩No.01]]> </address> 
        <telephone>13916732212</telephone>
      </card> 
      <card name="zhangsan" id="2">
        <sex>女</sex> 
        <address>
          <item type="家庭地址"><![CDATA[中国.北京.东直门外大街]]> </item> 
          <item type="单位地址"><![CDATA[中国.上海.田林路888号]]> </item>
        </address> 
        <telephone>010-123123</telephone>  
        <email type="工作">work@some-domain.com</email>
        <email type="私人"><![CDATA[private@some-domain.com]]></email>
      </card>
    </address-list>

    最后注意一点:dom4j支持xpath语法,但该特性需要jaxen包的支持(编译期不需要,仅运行时需要),所以需要在项目中引入该包,如果是maven项目,要加入

    <dependency>
       <groupId>jaxen</groupId>
       <artifactId>jaxen</artifactId>
       <version>1.1.3-redhat-2</version>
      </dependency>

    否则运行时会提示"类找不到"之类的错误

  • 相关阅读:
    HDU 5835 Danganronpa 贪心
    HDU 5842 Lweb and String 水题
    HDU 5832 A water problem 水题
    Codeforces Beta Round #14 (Div. 2) A. Letter 水题
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem K. UTF-8 Decoder 模拟题
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem I. Alien Rectangles 数学
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem H. Parallel Worlds 计算几何
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem F. Turning Grille 暴力
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem C. Cargo Transportation 暴力
    Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem G. k-palindrome dp
  • 原文地址:https://www.cnblogs.com/yjmyzz/p/2765312.html
Copyright © 2011-2022 走看看