加強Dom4j--讓XML處理更容易

加強Dom4j--讓XML處理更容易
 
Java處理XML的工具包中,Dom4j是佼佼者,可是使用起來仍是不夠簡潔。
爲更方便使用Dom4j處理XML,這裏作了一些工具類庫,放出來以供參考。
 
1、文件與字符串相互轉換的工具
處理XML文件讀取的問題,實際上這個是一個文本文件讀取的問題。
 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;

/**
* 字符串與文件相互轉換工具
*
* @author leizhimin 2009-11-11 15:54:18
*/

public class StringFileToolkit {
         private static Log log = LogFactory.getLog(StringFileToolkit. class);

         /**
         * 讀取輸入流爲一個內存字符串,保持文件原有的換行格式
         *
         * @param in            輸入流
         * @param charset 文件字符集編碼
         * @return 文件內容的字符串
         */

         public static String file2String(InputStream in, String charset) {
                StringBuffer sb = new StringBuffer();
                 try {
                        LineNumberReader reader = new LineNumberReader( new BufferedReader( new InputStreamReader(in, charset)));
                        String line;
                         while ((line = reader.readLine()) != null) {
                                sb.append(line).append(System.getProperty( "line.separator"));
                        }
                        reader.close();
                } catch (UnsupportedEncodingException e) {
                        log.error( "讀取文件爲一個內存字符串失敗,失敗緣由是使用了不支持的字符編碼" + charset, e);
                } catch (IOException e) {
                        log.error( "讀取文件爲一個內存字符串失敗,失敗緣由是讀取文件異常!", e);
                }
                 return sb.toString();
        }

         /**
         * 讀取文件爲一個內存字符串,保持文件原有的換行格式
         *
         * @param file        文件對象
         * @param charset 文件字符集編碼
         * @return 文件內容的字符串
         */

         public static String file2String(File file, String charset) {
                StringBuffer sb = new StringBuffer();
                 try {
                        LineNumberReader reader = new LineNumberReader( new BufferedReader( new InputStreamReader( new FileInputStream(file), charset)));
                        String line;
                         while ((line = reader.readLine()) != null) {
                                sb.append(line).append(System.getProperty( "line.separator"));
                        }
                        reader.close();
                } catch (UnsupportedEncodingException e) {
                        log.error( "讀取文件爲一個內存字符串失敗,失敗緣由是使用了不支持的字符編碼" + charset, e);
                } catch (FileNotFoundException e) {
                        log.error( "讀取文件爲一個內存字符串失敗,失敗緣由所給的文件" + file + "不存在!", e);
                } catch (IOException e) {
                        log.error( "讀取文件爲一個內存字符串失敗,失敗緣由是讀取文件異常!", e);
                }
                 return sb.toString();
        }

         /**
         * 將字符串存儲爲一個文件,當文件不存在時候,自動建立該文件,當文件已存在時候,重寫文件的內容,特定狀況下,還與操做系統的權限有關。
         *
         * @param text         字符串
         * @param distFile 存儲的目標文件
         * @return 當存儲正確無誤時返回true,不然返回false
         */

         public static boolean string2File(String text, File distFile) {
                 if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
                BufferedReader br = null;
                BufferedWriter bw = null;
                 boolean flag = true;
                 try {
                        br = new BufferedReader( new StringReader(text));
                        bw = new BufferedWriter( new FileWriter(distFile));
                         char buf[] = new char[1024 * 64];         //字符緩衝區
                         int len;
                         while ((len = br.read(buf)) != -1) {
                                bw.write(buf, 0, len);
                        }
                        bw.flush();
                        br.close();
                        bw.close();
                } catch (IOException e) {
                        flag = false;
                        log.error( "將字符串寫入文件發生異常!", e);
                }
                 return flag;
        }

         public static void main(String[] args) {
                String x = file2String( new File( "C:\\a.txt"), "GBK");
                System.out.println(x);

                 boolean b = string2File(x, new File( "C:\\b.txt"));
                System.out.println(b);
        }
}
 
2、Doc文檔的一些經常使用操做
 
構建Document文檔對象,刪除、添加XML元素,格式化XML。
 
package zzvcom.common;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;

/**
* XML便捷工具箱
*
* @author leizhimin 2009-11-11 16:26:19
*/

public class XmlToolkit {
         private static Log log = LogFactory.getLog(XmlToolkit. class);


         /**
         * 根據classpath下xml文件名建立一個XML文檔對象,並制定讀取字符集
         *
         * @param classPathFileName xml文件名稱,
         * @param charset                     xml文件字符集編碼
         * @return xml的字符串
         */

         public static Document makeDocument(String classPathFileName, String charset) {
                Document doc = null;
                 try {
                        InputStream in = XmlToolkit. class.getClassLoader().getResourceAsStream(classPathFileName);
                        String xml = StringFileToolkit.stream2String(in, charset);
                        doc = DocumentHelper.parseText(xml);
                } catch (Exception e) {
                        log.error( "解析XML發生錯誤,請檢查ClassPath下面的" + classPathFileName + "文件是否存在,格式是不是正確!");
                         throw new RuntimeException(e);
                }
                 return doc;
        }

         /**
         * 建立一個XML文檔對象
         *
         * @param xmlfile xml文件
         * @param charset xml文件字符集編碼
         * @return xml的字符串
         */

         public static Document makeDocument(File xmlfile, String charset) {
                Document doc = null;
                 try {
                        String xml = StringFileToolkit.file2String(xmlfile, charset);
                        doc = DocumentHelper.parseText(xml);
                } catch (Exception e) {
                        log.error( "解析XML發生錯誤,請檢查" + xmlfile.getPath() + "文件是否存在,格式是不是正確!");
                         throw new RuntimeException(e);
                }
                 return doc;
        }

         /**
         * 刪除文檔doc的指定路徑下的全部子節點(包含元素,屬性等)
         *
         * @param doc     文檔對象
         * @param xpath 指定元素的路徑
         * @return 刪除成功時返回true,不然false
         */

         public static boolean deleteNodes(Document doc, String xpath) {
                 boolean flag = true;
                 try {
                        List<Node> nlist = doc.selectNodes(xpath);
                         for (Node node : nlist) {
                                node.detach();
                        }
                } catch (Exception e) {
                        flag = false;
                }
                 return flag;
        }

         /**
         * 刪除一個父元素下全部的子節點(包含元素,屬性等)
         *
         * @param element 父元素
         * @return 刪除成功時返回true,不然false
         */

         public static boolean deleteChildren(Element element) {
                 boolean flag = true;
                 try {
                        List<Node> nlist = element.elements();
                         for (Node node : nlist) {
                                node.detach();
                        }
                } catch (Exception e) {
                        flag = false;
                }
                 return flag;
        }

         /**
         * 在指定文檔doc的xpath元素下面添加ename子元素,並給出子元素的text值
         *
         * @param doc        文檔對象
         * @param xpath    父元素的xpath
         * @param ename    所加入子元素名稱
         * @param evalue 所加入子元素的text值
         * @return 加入後的xml元素
         */

         public static Element addElement(Document doc, String xpath, String ename, String evalue) {
                Element element = null;
                Node n = (Node) doc.selectSingleNode(xpath);
                 if (n instanceof Element) {
                        Element e = (Element) n;
                        element = e.addElement(ename);
                        element.setText(evalue);
                }
                 return element;
        }

         /**
         * 在指定文檔doc的xpath元素下面添加xml文檔爲子元素
         *
         * @param doc     文檔對象
         * @param xpath 父元素的xpath
         * @param xml     要加入的xml文檔
         * @return 所加入後的xml元素
         */

         public static Element addElementByString(Document doc, String xpath, String xml) {
                Element subdoc = null;
                 try {
                        subdoc = DocumentHelper.parseText(xml).getRootElement();
                } catch (DocumentException e) {
                        e.printStackTrace();
                }
                Node n = (Node) doc.selectSingleNode(xpath);
                 if (n instanceof Element) {
                        Element e = (Element) n;
                        e.add(subdoc);
                        System.out.println(subdoc.getPath());
                }
                 return subdoc;
        }

         /**
         * 格式化XML文檔
         *
         * @param document xml文檔
         * @param charset    字符串的編碼
         * @return 格式化後XML字符串
         */

         public static String formatXML(Document document, String charset) {
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding(charset);
                StringWriter sw = new StringWriter();
                XMLWriter xw = new XMLWriter(sw, format);
                 try {
                        xw.write(document);
                        xw.flush();
                        xw.close();
                } catch (IOException e) {
                        log.error( "格式化XML文檔發生異常,請檢查!", e);
                }
                 return sw.toString();
        }
}
 
 
測試輸出結果:
/platscheme/scheme/vcom
<?xml version= "1.0" encoding= "GBK"?>
<platscheme>
        <schemeName/>
        <schemeId/>
        <platformname>1</platformname>
        <platformId>1</platformId>
        <updCapacity>1</updCapacity>
        <onlineCapacity>1</onlineCapacity>
        <delCapacity>1</delCapacity>
        <scheme><movies><del><movie mpeg= "" moviename="" generid= "0" onlinedate=""/>
                        </del></movies>
        <vcom>
  <ftpinfo>
    <serverip>127.0.0.1</serverip>
    <serverport>21</serverport>
    <username>ftpnv2cds1</username>
    <password>ftp</password>
  </ftpinfo>

  <webserviceinfo>
    <serverip>127.0.0.1</serverip>
    <serverport>8888</serverport>
  </webserviceinfo>

  <planinfo>
    <!--璁″垝緙栧彿-->
    <planid>filename</planid>
    <downloadfile>
      <!--闇�瑕佷笅杞界殑鏂囦歡淇℃伅-->
      <plandata plandataid= "1" filepath= "/" filename= "filename"/>
    </downloadfile>
  </planinfo>
</vcom></scheme>
</platscheme>
-----------------------------
<?xml version= "1.0" encoding= "UTF-8"?>

<platscheme>    
    <schemeName/>    
    <schemeId/>    
    <platformname>1</platformname>    
    <platformId>1</platformId>    
    <updCapacity>1</updCapacity>    
    <onlineCapacity>1</onlineCapacity>    
    <delCapacity>1</delCapacity>    
    <scheme>
        <movies>
            <del>
                <movie mpeg= "" moviename="" generid= "0" onlinedate=""/>    
            </del>
        </movies>    
        <vcom>    
            <ftpinfo>    
                <serverip>127.0.0.1</serverip>    
                <serverport>21</serverport>    
                <username>ftpnv2cds1</username>    
                <password>ftp</password>    
            </ftpinfo>    
            <webserviceinfo>    
                <serverip>127.0.0.1</serverip>    
                <serverport>8888</serverport>    
            </webserviceinfo>    
            <planinfo>    
                <!--璁″垝緙栧彿-->    
                <planid>filename</planid>    
                <downloadfile>    
                    <!--闇�瑕佷笅杞界殑鏂囦歡淇℃伅-->    
                    <plandata plandataid= "1" filepath= "/" filename= "filename"/>    
                </downloadfile>    
            </planinfo>    
        </vcom>
    </scheme>    
</platscheme>


Process finished with exit code 0
 
有了以上的擴展,結合Dom4j,處理XML的工做會變得至關輕鬆容易。
相關文章
相關標籤/搜索