Java操作XML文件 dom4j 篇

在項目中,我們很多都用到了xml文件,無論是參數配置還是與其它系統的數據交互。
今天就來講一下Java 中使用dom4j來操作XML文件。

我們需要引入的包:

//文件包
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
//工具包
import java.util.Iterator;
import java.util.List;
//dom4j包
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

1、將XML文件的內容轉化爲String

   /**
    * doc2String
    * 將xml文檔內容轉爲String
    * @return 字符串
    * @param document
    */

   public static String doc2String(Document document)
   {
      String s = "";
      try
      {
           //使用輸出流來進行轉化
           ByteArrayOutputStream out = new ByteArrayOutputStream();
           //使用GB2312編碼
           OutputFormat format = new OutputFormat("  ", true, "GB2312");
           XMLWriter writer = new XMLWriter(out, format);
           writer.write(document);
           s = out.toString("GB2312");
      }catch(Exception ex)
      {            
           ex.printStackTrace();
      }      
      return s;
   }

2、將符合XML格式的String 轉化爲XML Document

   /**
    * string2Document
    * 將字符串轉爲Document
    * @return 
    * @param s xml格式的字符串
    */

   public static Document string2Document(String s)
   {
      Document doc = null;
      try
      {
           doc = DocumentHelper.parseText(s);
      }catch(Exception ex)
      {            
           ex.printStackTrace();
      }
      return doc;
   }

3、將Document對象保存爲一個xml文件到本地

   /**
    * doc2XmlFile
    * 將Document對象保存爲一個xml文件到本地
    * @return true:保存成功  flase:失敗
    * @param filename 保存的文件名
    * @param document 需要保存的document對象
    */

   public static boolean doc2XmlFile(Document document,String filename)
   {
      boolean flag = true;
      try
      {
            /* 將document中的內容寫入文件中 */
            //默認爲UTF-8格式,指定爲"GB2312"
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("GB2312");
            XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);
            writer.write(document);
            writer.close();            
        }catch(Exception ex)
        {
            flag = false;
            ex.printStackTrace();
        }
        return flag;      
   }

4、將xml格式的字符串保存爲本地文件,如果字符串格式不符合xml規則,則返回失敗

   /**
    * string2XmlFile
    * 將xml格式的字符串保存爲本地文件,如果字符串格式不符合xml規則,則返回失敗
    * @return true:保存成功  flase:失敗
    * @param filename 保存的文件名
    * @param str 需要保存的字符串
    */

   public static boolean string2XmlFile(String str,String filename)
   {
      boolean flag = true;
      try
      {
         Document doc =  DocumentHelper.parseText(str);       
         flag = doc2XmlFile(doc,filename);
      }catch (Exception ex)
      {
         flag = false;
         ex.printStackTrace();
      }
      return flag;
   }

5、載入一個xml文檔

   /**
    * load
    * 載入一個xml文檔
    * @return 成功返回Document對象,失敗返回null
    * @param uri 文件路徑
    */

   public static Document load(String filename)
   {
      Document document = null;
      try 
      { 
          SAXReader saxReader = new SAXReader();
          document = saxReader.read(new File(filename));
      }
      catch (Exception ex){
          ex.printStackTrace();
      }  
      return document;
   }

 6、演示String保存爲xml文件

   /**
    * xmlWriteDemoByString
    * 演示String保存爲xml文件
    */

   public void xmlWriteDemoByString()
   {
      String s = "";
      /** xml格式標題 "<?xml version='1.0' encoding='GB2312'?>" 可以不用寫*/
      s = "<config>/r/n"
         +"   <ftp name='DongDian'>/r/n"
         +"     <ftp-host>127.0.0.1</ftp-host>/r/n"
         +"     <ftp-port>21</ftp-port>/r/n"
         +"     <ftp-user>cxl</ftp-user>/r/n"
         +"     <ftp-pwd>longshine</ftp-pwd>/r/n"
         +"     <!-- ftp最多嘗試連接次數 -->/r/n"
         +"     <ftp-try>50</ftp-try>/r/n"
         +"     <!-- ftp嘗試連接延遲時間 -->/r/n"
         +"     <ftp-delay>10</ftp-delay>/r/n"
         +"  </ftp>/r/n"
         +"</config>/r/n";
      //將文件生成到classes文件夾所在的目錄裏   
      string2XmlFile(s,"xmlWriteDemoByString.xml");   
      //將文件生成到classes文件夾裏   
      string2XmlFile(s,"classes/xmlWriteDemoByString.xml");  
   }

7、演示手動創建一個Document,並保存爲XML文件

   /**
    * 演示手動創建一個Document,並保存爲XML文件
    */

   public void xmlWriteDemoByDocument()
   {
        /** 建立document對象 */
        Document document = DocumentHelper.createDocument();
        /** 建立config根節點 */
        Element configElement = document.addElement("config");
        /** 建立ftp節點 */
        configElement.addComment("東電ftp配置");
        Element ftpElement = configElement.addElement("ftp");
        ftpElement.addAttribute("name","DongDian");
        /** ftp 屬性配置 */
        Element hostElement = ftpElement.addElement("ftp-host");
        hostElement.setText("127.0.0.1");
        (ftpElement.addElement("ftp-port")).setText("21");
        (ftpElement.addElement("ftp-user")).setText("cxl");
        (ftpElement.addElement("ftp-pwd")).setText("longshine");
        ftpElement.addComment("ftp最多嘗試連接次數");
        (ftpElement.addElement("ftp-try")).setText("50");
        ftpElement.addComment("ftp嘗試連接延遲時間");
        (ftpElement.addElement("ftp-delay")).setText("10");    
        /** 保存Document */
        doc2XmlFile(document,"classes/xmlWriteDemoByDocument.xml");
   }

8、演示讀取文件的具體某個節點的值

   /**
    *  演示讀取文件的具體某個節點的值 
    */

   public static void xmlReadDemo()
   {
      Document doc = load("classes/xmlWriteDemoByDocument.xml");
      //Element root = doc.getRootElement();
      /** 先用xpath查找所有ftp節點 並輸出它的name屬性值*/
      List list = doc.selectNodes("/config/ftp" );
      Iterator it = list.iterator();
      while(it.hasNext())
      {   
          Element ftpElement = (Element)it.next();
          System.out.println("ftp_name="+ftpElement.attribute("name").getValue());
      }
      /** 直接用屬性path取得name值 */
      list = doc.selectNodes("/config/ftp/@name" );
      it = list.iterator();
      while(it.hasNext())
      {   
          Attribute attribute = (Attribute)it.next();
          System.out.println("@name="+attribute.getValue());
      }
      /** 直接取得DongDian ftp的 ftp-host 的值 */
      list = doc.selectNodes("/config/ftp/ftp-host" );
      it = list.iterator();
      Element hostElement=(Element)it.next();
      System.out.println("DongDian's ftp_host="+hostElement.getText());
   }

9、修改或刪除某個值或屬性

/** ftp節點刪除ftp-host節點 */
ftpElement.remove(hostElement); 
/** ftp節點刪除name屬性 */
ftpElement.remove(nameAttribute);
/** 修改ftp-host的值 */
hostElement.setText("192.168.0.1"); 
/** 修改ftp節點name屬性的值 */
nameAttribute.setValue("ChiFeng");

From:http://hi.baidu.com/joecom/blog/item/8083b21c43eeec8b86d6b623.html

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章