Dom4j解析xml(二)

来源:互联网 发布:关于环保的数据 编辑:程序博客网 时间:2024/05/16 12:02

现在就Dom4j解析xml的一些语法做出例子分析;先通过写一个类将上篇的xml文件解析出来。            package cn.itcast.dom4j;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

//1. 将 dom4j.jar 文件加入到当前 Java 工程的 classPath 下
public class HelloDom4j {

 public static void main(String[] args) throws DocumentException {
  //2. 在 Dom4j 中, xml 文档对应 Document 对象
  
  //a. 得到 xml 文档代表的 Document 对象
  Document document = null;
  File file = null;
  
  file = new File("customers.xml");
        SAXReader reader = new SAXReader();
        document = reader.read(file);
       
        //System.out.println(document);
       
        //b. 得到 xml 文档的根元素
        Element root = ()document.getRootElement;
        String rootName = root.getName();
        //System.out.println("rootName: " + rootName);
        System.out.println("<" + rootName + ">");
       
        //c. 得到根结点的所有子节点
        List<Element> rootChildren = null;
        rootChildren = root.elements();
        //System.out.println("rootChildren.size: " + rootChildren.size());
       
        //d. 对所有的子节点进行遍历
        for(int i = 0; i < rootChildren.size(); i++){
         Element customerEle = rootChildren.get(i);
         //System.out.println(customerEle.getName());
         System.out.println("/t<" + customerEle.getName() + ">");
         
         Iterator<Element> it = customerEle.elementIterator();
         while(it.hasNext()){
          Element ele = it.next();
          //System.out.println(ele.getName());
          //得到元素的名字
          String eleName = ele.getName();
          //得到元素的文本值
          String eleText = ele.getText();
          
          System.out.println("/t/t<" + eleName + ">" +
            eleText +
            "</" + eleName + ">");
         }
         
         System.out.println("/t</" + customerEle.getName() + ">");
        }
       
        System.out.println("</" + rootName + ">");
 }

}

     最后运行的结果也就是上篇的xml文档。体会:在这个类中,我们不难发现,在解析文档的时候是根据xml的树结构进行解析的,而不是杂乱的。这个类中的四个步骤将是以后的增,改,删的基本步骤!其实能够深刻的理解这一思想,我们也就不难理解Dom4j解析xml的真正原理,在以后的WEB开发中用起来会如鱼的水!

现在再看下增加属性值及文本值的一个例子:

package cn.itcast.dom4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//任务:为 customers.xml 文档的 id = 102 的 Customer 节点添加一个 address 子节点<address>Shanghai</address>
public class InsertElement {

 public static void main(String[] args) throws DocumentException, IOException {
  // TODO Auto-generated method stub
  //1. 得到 customers.xml 代表的 Document 对象
  SAXReader reader = null;
  File file = null;
  Document document = null;
  
  reader = new SAXReader();
  file = new File("customers.xml");
  document = reader.read(file);
  
  //2. 得到 id = 102 的 Customer 节点
  Element custEle = null;
  
  List<Attribute> idAttrs = document.selectNodes("//customers/customer/@id");
  for(int i = 0; i < idAttrs.size(); i++){
   String idValue = idAttrs.get(i).getValue();
   if(idValue != null && idValue.equals("102")){
    custEle = idAttrs.get(i).getParent();
   }
  }
  
  System.out.println(custEle);
  
  //3. 为 custEle 添加一个子节点: <address></address>
  Element address = custEle.addElement("address");
  //4. 设置该节点的文本值
  address.setText("Shanghai");
  //4.1 设置子节点的属性
  address.addAttribute("id", "021");
  
  //5. 把更新后的 Document 对象写入到 customers.xml 文件中
  
  //5.1设置输出方式, 获取 OutputFormat 对象
  OutputFormat format = OutputFormat.createPrettyPrint();
  format.setEncoding("GB2312");
  //5.2 获取 XMLWriter 对象
  XMLWriter writer = new XMLWriter(new FileWriter( "customers.xml" ), format);
  //5.2 写入到文件中
        writer.write(document);
        //5.4 关闭 io 流
        writer.close();
       
      
 }

}

<customers>
  <customer id="103" sex="m">
   <name xmlns="Bob" />
   <age xmlns="32" />
   <email xmlns="Bob@163.com" />
  </customer>
  <customer id="102" sex="f">
   <name xmlns="Jerry" />
   <age xmlns="22" />
   <email xmlns="jerry@sohu.com" />
       <address id="021">Shanghai</address>    //这句为添加的句子
  </customer>
</customers>
    在这个例题中,最关键的一点就是第5步骤,把更新后的 Document 对象写入到 customers.xml 文件中的几种方法。还有个注意点就是在用到流写入文件的时候一定要用write.close();将流关闭!通过这个例子可以看出,删除,修改等等,只要理解其方法,这些类就并不难写!
 
对于Dom4j解析xml的例子就先体会到这里,由于本人是菜鸟,刚刚起飞,可能文章写的很没有火候,望能阅读本Blog的读者给予理解!
明天还有佟老师关于xml解析的课程内容,期待!!!!!!!!!!!!