本文從以下幾個基礎的方面介紹dom4j操作XML的使用小結,挺好!

 

本文從以下幾個基礎的方面介紹dom4j操作XML的使用小結:

  • [一] 讀取XML文件 的示例
  • [二] 讀取XML字符串 的示例
  • [三] 解析XML的document 的示例
  • [四] XML編碼格式轉換 的示例
  • [五] 輸出格式的自定義 的示例
  • [六] XML輸出文件的示例

 

[一]、讀取XML文件:

 

xml示例的文件d:/test/michael/dom4j_info.xml,內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <root>  
  3.     <info index="1" type="blog">  
  4.         <URL>http://sjsky.iteye.com</URL>  
  5.         <name id="sjsky">Michael</name>  
  6.         <categories>  
  7.             <category valule="java"/>  
  8.             <category valule="spring"/>  
  9.             <category valule="hibernate"/>  
  10.             <category valule="NoSQL"/>  
  11.             <category valule="MYSQL"/>  
  12.         </categories>  
  13.     </info>  
  14. </root>  

 讀取文件的Java代碼如下:

Java代碼 複製代碼 收藏代碼
  1. String fileName = "d:/test/michael/dom4j_info.xml";   
  2. try {   
  3.             SAXReader reader = new SAXReader();   
  4.             Document document = reader.read(new File(fileName));   
  5.             System.out.println("document轉化爲String輸出如下:");   
  6.             System.out.println(document.asXML());   
  7.         } catch (Exception e) {   
  8.             e.printStackTrace();   
  9.         }  
String fileName = "d:/test/michael/dom4j_info.xml";
try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fileName));
            System.out.println("document轉化爲String輸出如下:");
            System.out.println(document.asXML());
        } catch (Exception e) {
            e.printStackTrace();
        }

 

運行結果輸出如下:代碼 複製代碼 收藏代碼
  1. document轉化爲String輸出如下:   
  2. <?xml version="1.0" encoding="UTF-8"?>   
  3. <root>   
  4.     <info index="1" type="blog">   
  5.         <URL>http://sjsky.iteye.com</URL>   
  6.         <name id="sjsky">Michael</name>   
  7.         <categories>   
  8.             <category valule="java"/>   
  9.             <category valule="spring"/>   
  10.             <category valule="hibernate"/>   
  11.             <category valule="NoSQL"/>   
  12.             <category valule="MYSQL"/>   
  13.         </categories>   
  14.     </info>   
  15. </root>  

 

ps:一般默認以XML文件中encoding定義的編碼格式讀取文件

 

[二]、讀取XML字符串:

 

Java讀取String的demo代碼:

Java代碼 複製代碼 收藏代碼
  1. System.out.println("解析XML字符串DEMO");   
  2.  String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  3.          + "<URL>http://sjsky.iteye.com</URL>"  
  4.          + "<name id=\"sjsky\">Michael</name>"  
  5.          + "<categories><category valule=\"java\"/>"  
  6.          + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  7.          + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  8.          + "</categories></info></root>";   
  9.  try {   
  10.      Document document = DocumentHelper.parseText(xmlStr);   
  11.      System.out.println("document信息輸出,默認爲UTF-8的編碼:");   
  12.      System.out.println(document.asXML());   
  13.  } catch (Exception e) {   
  14.      e.printStackTrace();   
  15.  }  
       System.out.println("解析XML字符串DEMO");
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("document信息輸出,默認爲UTF-8的編碼:");
            System.out.println(document.asXML());
        } catch (Exception e) {
            e.printStackTrace();
        }
運行結果輸出如下:
解析XML字符串DEMO
document信息輸出,默認爲UTF-8的編碼:
<?xml version="1.0" encoding="UTF-8"?>
<root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>

ps:1.默認輸出編碼爲UTF-8

      2.輸出字符串格式定義參見本文 第[五]部分 

 

[三]、解析XML的Document

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * 解析文件  
  3.  * @blog http://sjsky.iteye.com  
  4.  * @param fileName  
  5.  */  
  6. public static void readXMLFile(String fileName) {   
  7.     try {   
  8.         SAXReader reader = new SAXReader();   
  9.         Document document = reader.read(new File(fileName));   
  10.         readXML(document);   
  11.     } catch (Exception e) {   
  12.         e.printStackTrace();   
  13.     }   
  14. }   
  15.   
  16. public static void readXML(Document document) {   
  17.     try {   
  18.         System.out.println("開始解析 XML Document:");   
  19.   
  20.         // 獲取跟節點   
  21.         Element rootEle = document.getRootElement();   
  22.         System.out.println("獲取跟節點Root:");   
  23.         System.out.println(rootEle.asXML());   
  24.   
  25.         // 根據名稱獲取Element   
  26.         Element info = rootEle.element("info");   
  27.         System.out.println("獲取Root下名稱爲info的子Element:");   
  28.         System.out.println(info.asXML());   
  29.   
  30.         // 根據名稱獲取List<Element>   
  31.         List<Element> infolist = rootEle.elements("info");   
  32.         System.out.println("和上面獲取的Element應該一致:");   
  33.         System.out.println(infolist.get(0).asXML());   
  34.   
  35.         // 獲取屬性值   
  36.         System.out.println("獲取指定屬性type的值 = " + info.attributeValue("type"));   
  37.   
  38.         // 獲取所有的屬性值   
  39.         for (int i = 0; i < info.attributeCount(); i++) {   
  40.             System.out.println("獲取所有的屬性和值: " + info.attribute(i).getName()   
  41.                     + " = " + info.attribute(i).getValue());   
  42.         }   
  43.         // XPath的功能展示   
  44.   
  45.         Node node1 = document.selectSingleNode("/root/info/name");   
  46.         System.out.println("根據XPath=/root/info/name獲取document下的ELement : "  
  47.                 + node1.asXML());   
  48.   
  49.         Node node2 = rootEle.selectSingleNode("info/name");   
  50.         System.out.println("根據XPath=info/name      獲取root下的ELement     : "  
  51.                 + node2.asXML());   
  52.   
  53.         Node node3 = rootEle.selectSingleNode("//info/name");   
  54.         System.out.println("根據XPath=//info/name    獲取root下的ELement     : "  
  55.                 + node3.asXML());   
  56.         System.out.println("上述三種方式獲取的結果應該是一致");   
  57.   
  58.         List<?> nodeList = rootEle   
  59.                 .selectNodes("//info/categories/category");   
  60.         System.out   
  61.                 .println("根據XPath=//info/categories/category獲取root下的List:");   
  62.         for (int i = 0; i < nodeList.size(); i++) {   
  63.             System.out.println(((Element) nodeList.get(i)).asXML());   
  64.         }   
  65.   
  66.     } catch (Exception e) {   
  67.         e.printStackTrace();   
  68.     }   
  69. }  
    /**
     * 解析文件
     * @blog http://sjsky.iteye.com
     * @param fileName
     */
    public static void readXMLFile(String fileName) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fileName));
            readXML(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readXML(Document document) {
        try {
            System.out.println("開始解析 XML Document:");

            // 獲取跟節點
            Element rootEle = document.getRootElement();
            System.out.println("獲取跟節點Root:");
            System.out.println(rootEle.asXML());

            // 根據名稱獲取Element
            Element info = rootEle.element("info");
            System.out.println("獲取Root下名稱爲info的子Element:");
            System.out.println(info.asXML());

            // 根據名稱獲取List<Element>
            List<Element> infolist = rootEle.elements("info");
            System.out.println("和上面獲取的Element應該一致:");
            System.out.println(infolist.get(0).asXML());

            // 獲取屬性值
            System.out.println("獲取指定屬性type的值 = " + info.attributeValue("type"));

            // 獲取所有的屬性值
            for (int i = 0; i < info.attributeCount(); i++) {
                System.out.println("獲取所有的屬性和值: " + info.attribute(i).getName()
                        + " = " + info.attribute(i).getValue());
            }
            // XPath的功能展示

            Node node1 = document.selectSingleNode("/root/info/name");
            System.out.println("根據XPath=/root/info/name獲取document下的ELement : "
                    + node1.asXML());

            Node node2 = rootEle.selectSingleNode("info/name");
            System.out.println("根據XPath=info/name      獲取root下的ELement     : "
                    + node2.asXML());

            Node node3 = rootEle.selectSingleNode("//info/name");
            System.out.println("根據XPath=//info/name    獲取root下的ELement     : "
                    + node3.asXML());
            System.out.println("上述三種方式獲取的結果應該是一致");

            List<?> nodeList = rootEle
                    .selectNodes("//info/categories/category");
            System.out
                    .println("根據XPath=//info/categories/category獲取root下的List:");
            for (int i = 0; i < nodeList.size(); i++) {
                System.out.println(((Element) nodeList.get(i)).asXML());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  
運行結果如下:代碼 複製代碼 收藏代碼
  1. 開始解析 XML Document:   
  2. 獲取跟節點Root:   
  3. <root>   
  4.     <info index="1" type="blog">   
  5.         <URL>http://sjsky.iteye.com</URL>   
  6.         <name id="sjsky">Michael</name>   
  7.         <categories>   
  8.             <category valule="java"/>   
  9.             <category valule="spring"/>   
  10.             <category valule="hibernate"/>   
  11.             <category valule="NoSQL"/>   
  12.             <category valule="MYSQL"/>   
  13.         </categories>   
  14.     </info>   
  15. </root>   
  16. 獲取Root下名稱爲info的子Element:   
  17. <info index="1" type="blog">   
  18.         <URL>http://sjsky.iteye.com</URL>   
  19.         <name id="sjsky">Michael</name>   
  20.         <categories>   
  21.             <category valule="java"/>   
  22.             <category valule="spring"/>   
  23.             <category valule="hibernate"/>   
  24.             <category valule="NoSQL"/>   
  25.             <category valule="MYSQL"/>   
  26.         </categories>   
  27.     </info>   
  28. 和上面獲取的Element應該一致:   
  29. <info index="1" type="blog">   
  30.         <URL>http://sjsky.iteye.com</URL>   
  31.         <name id="sjsky">Michael</name>   
  32.         <categories>   
  33.             <category valule="java"/>   
  34.             <category valule="spring"/>   
  35.             <category valule="hibernate"/>   
  36.             <category valule="NoSQL"/>   
  37.             <category valule="MYSQL"/>   
  38.         </categories>   
  39.     </info>   
  40. 獲取指定屬性type的值 = blog   
  41. 獲取所有的屬性和值: index = 1  
  42. 獲取所有的屬性和值: type = blog   
  43. 根據XPath=/root/info/name獲取document下的ELement : <name id="sjsky">Michael</name>   
  44. 根據XPath=info/name      獲取root下的ELement     : <name id="sjsky">Michael</name>   
  45. 根據XPath=//info/name    獲取root下的ELement     : <name id="sjsky">Michael</name>   
  46. 上述三種方式獲取的結果應該是一致   
  47. 根據XPath=//info/categories/category獲取root下的List:   
  48. <category valule="java"/>   
  49. <category valule="spring"/>   
  50. <category valule="hibernate"/>   
  51. <category valule="NoSQL"/>   
  52. <category valule="MYSQL"/>  

ps:1. XPath的使用依賴lib包:jaxen.jar

      2. XPath的簡單介紹說明(以後有機會做個詳細介紹)

  •  nodename 選取此節點的所有子節點(相對路徑)
  • / 從根節點選取(絕對路徑)         
  • // 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置
  • .  選取當前節點
  • .. 選取當前節點的父節點
  • @  選取屬性

 

[四]、XML編碼格式轉換:

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @param args  
  4.  */  
  5. public static void main(String[] args) {   
  6.   
  7.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  8.             + "<URL>http://sjsky.iteye.com</URL>"  
  9.             + "<name id=\"sjsky\">Michael</name>"  
  10.             + "<categories><category valule=\"java\"/>"  
  11.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  12.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  13.             + "</categories></info></root>";   
  14.   
  15.     System.out.println("XML編碼轉化DEMO");   
  16.     try {   
  17.         Document document = DocumentHelper.parseText(xmlStr);   
  18.         System.out.println("默認爲UTF-8的編碼,輸出內容如下:");   
  19.         System.out.println(document.asXML());   
  20.         System.out.println("編碼轉化爲gb2312後,輸出內容如下:");   
  21.         String encodeStr = encodeXml(xmlStr, "gb2312");   
  22.         System.out.println(encodeStr);   
  23.   
  24.     } catch (Exception e) {   
  25.         e.printStackTrace();   
  26.     }   
  27.     System.out.println("DEMO End---------------------");   
  28. }  
    /**
     * @blog http://sjsky.iteye.com
     * @param args
     */
    public static void main(String[] args) {

        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML編碼轉化DEMO");
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("默認爲UTF-8的編碼,輸出內容如下:");
            System.out.println(document.asXML());
            System.out.println("編碼轉化爲gb2312後,輸出內容如下:");
            String encodeStr = encodeXml(xmlStr, "gb2312");
            System.out.println(encodeStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("DEMO End---------------------");
    }

 

運行結果如下:代碼 複製代碼 收藏代碼
  1. XML編碼轉化DEMO   
  2. 默認爲UTF-8的編碼,輸出內容如下:   
  3. <?xml version="1.0" encoding="UTF-8"?>   
  4. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>   
  5. 編碼轉化爲gb2312後,輸出內容如下:   
  6. <?xml version="1.0" encoding="gb2312"?>   
  7.   
  8. <root>   
  9.   <info index="1" type="blog">   
  10.     <URL>http://sjsky.iteye.com</URL>   
  11.     <name id="sjsky">Michael</name>   
  12.     <categories>   
  13.       <category valule="java"/>   
  14.       <category valule="spring"/>   
  15.       <category valule="hibernate"/>   
  16.       <category valule="NoSQL"/>   
  17.       <category valule="MYSQL"/>   
  18.     </categories>   
  19.   </info>   
  20. </root>   
  21.   
  22. DEMO End---------------------  

 

[五]、XML輸出格式的定義:

 

  • OutputFormat compactFormat = OutputFormat.createCompactFormat(); 緊湊的格式
  • OutputFormat prettyFormat = OutputFormat.createPrettyPrint(); 優雅具有層次的格式

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @param args  
  4.  */  
  5. public static void main(String[] args) {   
  6.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  7.             + "<URL>http://sjsky.iteye.com</URL>"  
  8.             + "<name id=\"sjsky\">Michael</name>"  
  9.             + "<categories><category valule=\"java\"/>"  
  10.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  11.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  12.             + "</categories></info></root>";   
  13.   
  14.     System.out.println("XML輸出格式定義Demo:");   
  15.     try {   
  16.         Document document = DocumentHelper.parseText(xmlStr);   
  17.         System.out.println("轉換爲優雅層次的格式輸出:");   
  18.         OutputFormat prettyFormat = OutputFormat.createPrettyPrint();   
  19.         String xmlPretty = xmlOutputFormat(document, prettyFormat);   
  20.         System.out.println(xmlPretty);   
  21.   
  22.         System.out.println("轉換爲緊湊格式輸出:");   
  23.         OutputFormat compactFormat = OutputFormat.createCompactFormat();   
  24.         String xmlCompact = xmlOutputFormat(document, compactFormat);   
  25.         System.out.println(xmlCompact);   
  26.     } catch (Exception e) {   
  27.         e.printStackTrace();   
  28.     }   
  29.   
  30.     System.out.println("DEMO End---------------------");   
  31. }   
  32.   
  33. /**  
  34.  * XML 輸出格式轉換  
  35.  * @param document  
  36.  * @param opFormat  
  37.  * @return String  
  38.  */  
  39. public static String xmlOutputFormat(Document document,   
  40.         OutputFormat opFormat) {   
  41.     // 具有層次的格式輸出   
  42.     // OutputFormat format = OutputFormat.createPrettyPrint();   
  43.     // 緊湊的格式輸出   
  44.     // OutputFormat format = OutputFormat.createCompactFormat();   
  45.     StringWriter sw = new StringWriter();   
  46.     try {   
  47.         XMLWriter writer = new XMLWriter(opFormat);   
  48.         writer.setWriter(sw);   
  49.         writer.write(document);   
  50.     } catch (Exception e) {   
  51.         e.printStackTrace();   
  52.     }   
  53.     return sw.toString();   
  54. }  
    /**
     * @blog http://sjsky.iteye.com
     * @param args
     */
    public static void main(String[] args) {
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML輸出格式定義Demo:");
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("轉換爲優雅層次的格式輸出:");
            OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
            String xmlPretty = xmlOutputFormat(document, prettyFormat);
            System.out.println(xmlPretty);

            System.out.println("轉換爲緊湊格式輸出:");
            OutputFormat compactFormat = OutputFormat.createCompactFormat();
            String xmlCompact = xmlOutputFormat(document, compactFormat);
            System.out.println(xmlCompact);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DEMO End---------------------");
    }

    /**
     * XML 輸出格式轉換
     * @param document
     * @param opFormat
     * @return String
     */
    public static String xmlOutputFormat(Document document,
            OutputFormat opFormat) {
        // 具有層次的格式輸出
        // OutputFormat format = OutputFormat.createPrettyPrint();
        // 緊湊的格式輸出
        // OutputFormat format = OutputFormat.createCompactFormat();
        StringWriter sw = new StringWriter();
        try {
            XMLWriter writer = new XMLWriter(opFormat);
            writer.setWriter(sw);
            writer.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

 

運行結果輸出如下:代碼 複製代碼 收藏代碼
  1. XML輸出格式定義Demo:   
  2. 轉換爲優雅層次的格式輸出:   
  3. <?xml version="1.0" encoding="UTF-8"?>   
  4.   
  5. <root>   
  6.   <info index="1" type="blog">   
  7.     <URL>http://sjsky.iteye.com</URL>   
  8.     <name id="sjsky">Michael</name>   
  9.     <categories>   
  10.       <category valule="java"/>   
  11.       <category valule="spring"/>   
  12.       <category valule="hibernate"/>   
  13.       <category valule="NoSQL"/>   
  14.       <category valule="MYSQL"/>   
  15.     </categories>   
  16.   </info>   
  17. </root>   
  18.   
  19. 轉換爲緊湊格式輸出:   
  20. <?xml version="1.0" encoding="UTF-8"?>   
  21. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>   
  22. DEMO End---------------------  

 

[六]、XML輸出文件:

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @author Michael  
  4.  * @param args  
  5.  */  
  6. public static void main(String[] args) {   
  7.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  8.             + "<URL>http://sjsky.iteye.com</URL>"  
  9.             + "<name id=\"sjsky\">Michael</name>"  
  10.             + "<categories><category valule=\"java\"/>"  
  11.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  12.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  13.             + "</categories></info></root>";   
  14.   
  15.     System.out.println("XML輸出文件:");   
  16.     String outFileName = "d:/test/michael/";   
  17.     try {   
  18.         Document document = DocumentHelper.parseText(xmlStr);   
  19.         xmlWriteXMLDoc(outFileName+"dom4j_info_out1.xml", document);   
  20.            
  21.         fileWriteXMLDoc(outFileName+"dom4j_info_out2.xml", document);   
  22.            
  23.     } catch (Exception e) {   
  24.         e.printStackTrace();   
  25.     }   
  26.   
  27.     System.out.println("DEMO End---------------------");   
  28. }   
  29.   
  30. /**  
  31.  *   
  32.  * @param fileName  
  33.  * @param document  
  34.  */  
  35. public static void xmlWriteXMLDoc(String fileName, Document document) {   
  36.     XMLWriter writer = null;   
  37.     try {   
  38.         //writer = new XMLWriter(new FileWriter(fileName));   
  39.         //writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createCompactFormat());   
  40.         writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createPrettyPrint());   
  41.         writer.write(document);   
  42.   
  43.     } catch (Exception e) {   
  44.         e.printStackTrace();   
  45.     } finally {   
  46.         try {   
  47.             if (null != writer) {   
  48.                 writer.close();   
  49.             }   
  50.         } catch (Exception e) {   
  51.             e.printStackTrace();   
  52.         }   
  53.     }   
  54. }   
  55.   
  56. /**  
  57.  *   
  58.  * @param fileName  
  59.  * @param document  
  60.  */  
  61. public static void fileWriteXMLDoc(String fileName, Document document) {   
  62.     FileWriter fw = null;   
  63.     try {   
  64.         fw = new FileWriter(fileName);   
  65.         document.write(fw);   
  66.     } catch (Exception e) {   
  67.         e.printStackTrace();   
  68.     } finally {   
  69.         try {   
  70.             if (null != fw) {   
  71.                 fw.close();   
  72.             }   
  73.         } catch (Exception e) {   
  74.             e.printStackTrace();   
  75.         }   
  76.     }   
  77. }  
    /**
     * @blog http://sjsky.iteye.com
     * @author Michael
     * @param args
     */
    public static void main(String[] args) {
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML輸出文件:");
        String outFileName = "d:/test/michael/";
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            xmlWriteXMLDoc(outFileName+"dom4j_info_out1.xml", document);
            
            fileWriteXMLDoc(outFileName+"dom4j_info_out2.xml", document);
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DEMO End---------------------");
    }

    /**
     * 
     * @param fileName
     * @param document
     */
    public static void xmlWriteXMLDoc(String fileName, Document document) {
        XMLWriter writer = null;
        try {
            //writer = new XMLWriter(new FileWriter(fileName));
            //writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createCompactFormat());
            writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createPrettyPrint());
            writer.write(document);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != writer) {
                    writer.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param fileName
     * @param document
     */
    public static void fileWriteXMLDoc(String fileName, Document document) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(fileName);
            document.write(fw);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fw) {
                    fw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

生成的dom4j_info_out1.xml文件內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <root>  
  4.   <info index="1" type="blog">  
  5.     <URL>http://sjsky.iteye.com</URL>  
  6.     <name id="sjsky">Michael</name>  
  7.     <categories>  
  8.       <category valule="java"/>  
  9.       <category valule="spring"/>  
  10.       <category valule="hibernate"/>  
  11.       <category valule="NoSQL"/>  
  12.       <category valule="MYSQL"/>  
  13.     </categories>  
  14.   </info>  
  15. </root>  

 

生成的dom4j_info_out2.xml文件內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>  

到此有關dom4j的簡單應用基本介紹完了,希望給新接觸的tx有所幫助。

本文從以下幾個基礎的方面介紹dom4j操作XML的使用小結:

  • [一] 讀取XML文件 的示例
  • [二] 讀取XML字符串 的示例
  • [三] 解析XML的document 的示例
  • [四] XML編碼格式轉換 的示例
  • [五] 輸出格式的自定義 的示例
  • [六] XML輸出文件的示例

 

[一]、讀取XML文件:

 

xml示例的文件d:/test/michael/dom4j_info.xml,內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <root>  
  3.     <info index="1" type="blog">  
  4.         <URL>http://sjsky.iteye.com</URL>  
  5.         <name id="sjsky">Michael</name>  
  6.         <categories>  
  7.             <category valule="java"/>  
  8.             <category valule="spring"/>  
  9.             <category valule="hibernate"/>  
  10.             <category valule="NoSQL"/>  
  11.             <category valule="MYSQL"/>  
  12.         </categories>  
  13.     </info>  
  14. </root>  

 讀取文件的Java代碼如下:

Java代碼 複製代碼 收藏代碼
  1. String fileName = "d:/test/michael/dom4j_info.xml";   
  2. try {   
  3.             SAXReader reader = new SAXReader();   
  4.             Document document = reader.read(new File(fileName));   
  5.             System.out.println("document轉化爲String輸出如下:");   
  6.             System.out.println(document.asXML());   
  7.         } catch (Exception e) {   
  8.             e.printStackTrace();   
  9.         }  
String fileName = "d:/test/michael/dom4j_info.xml";
try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fileName));
            System.out.println("document轉化爲String輸出如下:");
            System.out.println(document.asXML());
        } catch (Exception e) {
            e.printStackTrace();
        }

 

運行結果輸出如下:代碼 複製代碼 收藏代碼
  1. document轉化爲String輸出如下:   
  2. <?xml version="1.0" encoding="UTF-8"?>   
  3. <root>   
  4.     <info index="1" type="blog">   
  5.         <URL>http://sjsky.iteye.com</URL>   
  6.         <name id="sjsky">Michael</name>   
  7.         <categories>   
  8.             <category valule="java"/>   
  9.             <category valule="spring"/>   
  10.             <category valule="hibernate"/>   
  11.             <category valule="NoSQL"/>   
  12.             <category valule="MYSQL"/>   
  13.         </categories>   
  14.     </info>   
  15. </root>  

 

ps:一般默認以XML文件中encoding定義的編碼格式讀取文件

 

[二]、讀取XML字符串:

 

Java讀取String的demo代碼:

Java代碼 複製代碼 收藏代碼
  1. System.out.println("解析XML字符串DEMO");   
  2.  String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  3.          + "<URL>http://sjsky.iteye.com</URL>"  
  4.          + "<name id=\"sjsky\">Michael</name>"  
  5.          + "<categories><category valule=\"java\"/>"  
  6.          + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  7.          + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  8.          + "</categories></info></root>";   
  9.  try {   
  10.      Document document = DocumentHelper.parseText(xmlStr);   
  11.      System.out.println("document信息輸出,默認爲UTF-8的編碼:");   
  12.      System.out.println(document.asXML());   
  13.  } catch (Exception e) {   
  14.      e.printStackTrace();   
  15.  }  
       System.out.println("解析XML字符串DEMO");
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("document信息輸出,默認爲UTF-8的編碼:");
            System.out.println(document.asXML());
        } catch (Exception e) {
            e.printStackTrace();
        }
運行結果輸出如下:
解析XML字符串DEMO
document信息輸出,默認爲UTF-8的編碼:
<?xml version="1.0" encoding="UTF-8"?>
<root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>

ps:1.默認輸出編碼爲UTF-8

      2.輸出字符串格式定義參見本文 第[五]部分 

 

[三]、解析XML的Document

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * 解析文件  
  3.  * @blog http://sjsky.iteye.com  
  4.  * @param fileName  
  5.  */  
  6. public static void readXMLFile(String fileName) {   
  7.     try {   
  8.         SAXReader reader = new SAXReader();   
  9.         Document document = reader.read(new File(fileName));   
  10.         readXML(document);   
  11.     } catch (Exception e) {   
  12.         e.printStackTrace();   
  13.     }   
  14. }   
  15.   
  16. public static void readXML(Document document) {   
  17.     try {   
  18.         System.out.println("開始解析 XML Document:");   
  19.   
  20.         // 獲取跟節點   
  21.         Element rootEle = document.getRootElement();   
  22.         System.out.println("獲取跟節點Root:");   
  23.         System.out.println(rootEle.asXML());   
  24.   
  25.         // 根據名稱獲取Element   
  26.         Element info = rootEle.element("info");   
  27.         System.out.println("獲取Root下名稱爲info的子Element:");   
  28.         System.out.println(info.asXML());   
  29.   
  30.         // 根據名稱獲取List<Element>   
  31.         List<Element> infolist = rootEle.elements("info");   
  32.         System.out.println("和上面獲取的Element應該一致:");   
  33.         System.out.println(infolist.get(0).asXML());   
  34.   
  35.         // 獲取屬性值   
  36.         System.out.println("獲取指定屬性type的值 = " + info.attributeValue("type"));   
  37.   
  38.         // 獲取所有的屬性值   
  39.         for (int i = 0; i < info.attributeCount(); i++) {   
  40.             System.out.println("獲取所有的屬性和值: " + info.attribute(i).getName()   
  41.                     + " = " + info.attribute(i).getValue());   
  42.         }   
  43.         // XPath的功能展示   
  44.   
  45.         Node node1 = document.selectSingleNode("/root/info/name");   
  46.         System.out.println("根據XPath=/root/info/name獲取document下的ELement : "  
  47.                 + node1.asXML());   
  48.   
  49.         Node node2 = rootEle.selectSingleNode("info/name");   
  50.         System.out.println("根據XPath=info/name      獲取root下的ELement     : "  
  51.                 + node2.asXML());   
  52.   
  53.         Node node3 = rootEle.selectSingleNode("//info/name");   
  54.         System.out.println("根據XPath=//info/name    獲取root下的ELement     : "  
  55.                 + node3.asXML());   
  56.         System.out.println("上述三種方式獲取的結果應該是一致");   
  57.   
  58.         List<?> nodeList = rootEle   
  59.                 .selectNodes("//info/categories/category");   
  60.         System.out   
  61.                 .println("根據XPath=//info/categories/category獲取root下的List:");   
  62.         for (int i = 0; i < nodeList.size(); i++) {   
  63.             System.out.println(((Element) nodeList.get(i)).asXML());   
  64.         }   
  65.   
  66.     } catch (Exception e) {   
  67.         e.printStackTrace();   
  68.     }   
  69. }  
    /**
     * 解析文件
     * @blog http://sjsky.iteye.com
     * @param fileName
     */
    public static void readXMLFile(String fileName) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fileName));
            readXML(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void readXML(Document document) {
        try {
            System.out.println("開始解析 XML Document:");

            // 獲取跟節點
            Element rootEle = document.getRootElement();
            System.out.println("獲取跟節點Root:");
            System.out.println(rootEle.asXML());

            // 根據名稱獲取Element
            Element info = rootEle.element("info");
            System.out.println("獲取Root下名稱爲info的子Element:");
            System.out.println(info.asXML());

            // 根據名稱獲取List<Element>
            List<Element> infolist = rootEle.elements("info");
            System.out.println("和上面獲取的Element應該一致:");
            System.out.println(infolist.get(0).asXML());

            // 獲取屬性值
            System.out.println("獲取指定屬性type的值 = " + info.attributeValue("type"));

            // 獲取所有的屬性值
            for (int i = 0; i < info.attributeCount(); i++) {
                System.out.println("獲取所有的屬性和值: " + info.attribute(i).getName()
                        + " = " + info.attribute(i).getValue());
            }
            // XPath的功能展示

            Node node1 = document.selectSingleNode("/root/info/name");
            System.out.println("根據XPath=/root/info/name獲取document下的ELement : "
                    + node1.asXML());

            Node node2 = rootEle.selectSingleNode("info/name");
            System.out.println("根據XPath=info/name      獲取root下的ELement     : "
                    + node2.asXML());

            Node node3 = rootEle.selectSingleNode("//info/name");
            System.out.println("根據XPath=//info/name    獲取root下的ELement     : "
                    + node3.asXML());
            System.out.println("上述三種方式獲取的結果應該是一致");

            List<?> nodeList = rootEle
                    .selectNodes("//info/categories/category");
            System.out
                    .println("根據XPath=//info/categories/category獲取root下的List:");
            for (int i = 0; i < nodeList.size(); i++) {
                System.out.println(((Element) nodeList.get(i)).asXML());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  

運行結果如下:代碼 複製代碼 收藏代碼
  1. 開始解析 XML Document:   
  2. 獲取跟節點Root:   
  3. <root>   
  4.     <info index="1" type="blog">   
  5.         <URL>http://sjsky.iteye.com</URL>   
  6.         <name id="sjsky">Michael</name>   
  7.         <categories>   
  8.             <category valule="java"/>   
  9.             <category valule="spring"/>   
  10.             <category valule="hibernate"/>   
  11.             <category valule="NoSQL"/>   
  12.             <category valule="MYSQL"/>   
  13.         </categories>   
  14.     </info>   
  15. </root>   
  16. 獲取Root下名稱爲info的子Element:   
  17. <info index="1" type="blog">   
  18.         <URL>http://sjsky.iteye.com</URL>   
  19.         <name id="sjsky">Michael</name>   
  20.         <categories>   
  21.             <category valule="java"/>   
  22.             <category valule="spring"/>   
  23.             <category valule="hibernate"/>   
  24.             <category valule="NoSQL"/>   
  25.             <category valule="MYSQL"/>   
  26.         </categories>   
  27.     </info>   
  28. 和上面獲取的Element應該一致:   
  29. <info index="1" type="blog">   
  30.         <URL>http://sjsky.iteye.com</URL>   
  31.         <name id="sjsky">Michael</name>   
  32.         <categories>   
  33.             <category valule="java"/>   
  34.             <category valule="spring"/>   
  35.             <category valule="hibernate"/>   
  36.             <category valule="NoSQL"/>   
  37.             <category valule="MYSQL"/>   
  38.         </categories>   
  39.     </info>   
  40. 獲取指定屬性type的值 = blog   
  41. 獲取所有的屬性和值: index = 1  
  42. 獲取所有的屬性和值: type = blog   
  43. 根據XPath=/root/info/name獲取document下的ELement : <name id="sjsky">Michael</name>   
  44. 根據XPath=info/name      獲取root下的ELement     : <name id="sjsky">Michael</name>   
  45. 根據XPath=//info/name    獲取root下的ELement     : <name id="sjsky">Michael</name>   
  46. 上述三種方式獲取的結果應該是一致   
  47. 根據XPath=//info/categories/category獲取root下的List:   
  48. <category valule="java"/>   
  49. <category valule="spring"/>   
  50. <category valule="hibernate"/>   
  51. <category valule="NoSQL"/>   
  52. <category valule="MYSQL"/>  

ps:1. XPath的使用依賴lib包:jaxen.jar

      2. XPath的簡單介紹說明(以後有機會做個詳細介紹)

  •  nodename 選取此節點的所有子節點(相對路徑)
  • / 從根節點選取(絕對路徑)         
  • // 從匹配選擇的當前節點選擇文檔中的節點,而不考慮它們的位置
  • .  選取當前節點
  • .. 選取當前節點的父節點
  • @  選取屬性

 

[四]、XML編碼格式轉換:

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @param args  
  4.  */  
  5. public static void main(String[] args) {   
  6.   
  7.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  8.             + "<URL>http://sjsky.iteye.com</URL>"  
  9.             + "<name id=\"sjsky\">Michael</name>"  
  10.             + "<categories><category valule=\"java\"/>"  
  11.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  12.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  13.             + "</categories></info></root>";   
  14.   
  15.     System.out.println("XML編碼轉化DEMO");   
  16.     try {   
  17.         Document document = DocumentHelper.parseText(xmlStr);   
  18.         System.out.println("默認爲UTF-8的編碼,輸出內容如下:");   
  19.         System.out.println(document.asXML());   
  20.         System.out.println("編碼轉化爲gb2312後,輸出內容如下:");   
  21.         String encodeStr = encodeXml(xmlStr, "gb2312");   
  22.         System.out.println(encodeStr);   
  23.   
  24.     } catch (Exception e) {   
  25.         e.printStackTrace();   
  26.     }   
  27.     System.out.println("DEMO End---------------------");   
  28. }  
    /**
     * @blog http://sjsky.iteye.com
     * @param args
     */
    public static void main(String[] args) {

        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML編碼轉化DEMO");
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("默認爲UTF-8的編碼,輸出內容如下:");
            System.out.println(document.asXML());
            System.out.println("編碼轉化爲gb2312後,輸出內容如下:");
            String encodeStr = encodeXml(xmlStr, "gb2312");
            System.out.println(encodeStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("DEMO End---------------------");
    }

 

運行結果如下:代碼 複製代碼 收藏代碼
  1. XML編碼轉化DEMO   
  2. 默認爲UTF-8的編碼,輸出內容如下:   
  3. <?xml version="1.0" encoding="UTF-8"?>   
  4. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>   
  5. 編碼轉化爲gb2312後,輸出內容如下:   
  6. <?xml version="1.0" encoding="gb2312"?>   
  7.   
  8. <root>   
  9.   <info index="1" type="blog">   
  10.     <URL>http://sjsky.iteye.com</URL>   
  11.     <name id="sjsky">Michael</name>   
  12.     <categories>   
  13.       <category valule="java"/>   
  14.       <category valule="spring"/>   
  15.       <category valule="hibernate"/>   
  16.       <category valule="NoSQL"/>   
  17.       <category valule="MYSQL"/>   
  18.     </categories>   
  19.   </info>   
  20. </root>   
  21.   
  22. DEMO End---------------------  

 

[五]、XML輸出格式的定義:

 

  • OutputFormat compactFormat = OutputFormat.createCompactFormat(); 緊湊的格式
  • OutputFormat prettyFormat = OutputFormat.createPrettyPrint(); 優雅具有層次的格式

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @param args  
  4.  */  
  5. public static void main(String[] args) {   
  6.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  7.             + "<URL>http://sjsky.iteye.com</URL>"  
  8.             + "<name id=\"sjsky\">Michael</name>"  
  9.             + "<categories><category valule=\"java\"/>"  
  10.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  11.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  12.             + "</categories></info></root>";   
  13.   
  14.     System.out.println("XML輸出格式定義Demo:");   
  15.     try {   
  16.         Document document = DocumentHelper.parseText(xmlStr);   
  17.         System.out.println("轉換爲優雅層次的格式輸出:");   
  18.         OutputFormat prettyFormat = OutputFormat.createPrettyPrint();   
  19.         String xmlPretty = xmlOutputFormat(document, prettyFormat);   
  20.         System.out.println(xmlPretty);   
  21.   
  22.         System.out.println("轉換爲緊湊格式輸出:");   
  23.         OutputFormat compactFormat = OutputFormat.createCompactFormat();   
  24.         String xmlCompact = xmlOutputFormat(document, compactFormat);   
  25.         System.out.println(xmlCompact);   
  26.     } catch (Exception e) {   
  27.         e.printStackTrace();   
  28.     }   
  29.   
  30.     System.out.println("DEMO End---------------------");   
  31. }   
  32.   
  33. /**  
  34.  * XML 輸出格式轉換  
  35.  * @param document  
  36.  * @param opFormat  
  37.  * @return String  
  38.  */  
  39. public static String xmlOutputFormat(Document document,   
  40.         OutputFormat opFormat) {   
  41.     // 具有層次的格式輸出   
  42.     // OutputFormat format = OutputFormat.createPrettyPrint();   
  43.     // 緊湊的格式輸出   
  44.     // OutputFormat format = OutputFormat.createCompactFormat();   
  45.     StringWriter sw = new StringWriter();   
  46.     try {   
  47.         XMLWriter writer = new XMLWriter(opFormat);   
  48.         writer.setWriter(sw);   
  49.         writer.write(document);   
  50.     } catch (Exception e) {   
  51.         e.printStackTrace();   
  52.     }   
  53.     return sw.toString();   
  54. }  
    /**
     * @blog http://sjsky.iteye.com
     * @param args
     */
    public static void main(String[] args) {
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML輸出格式定義Demo:");
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            System.out.println("轉換爲優雅層次的格式輸出:");
            OutputFormat prettyFormat = OutputFormat.createPrettyPrint();
            String xmlPretty = xmlOutputFormat(document, prettyFormat);
            System.out.println(xmlPretty);

            System.out.println("轉換爲緊湊格式輸出:");
            OutputFormat compactFormat = OutputFormat.createCompactFormat();
            String xmlCompact = xmlOutputFormat(document, compactFormat);
            System.out.println(xmlCompact);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DEMO End---------------------");
    }

    /**
     * XML 輸出格式轉換
     * @param document
     * @param opFormat
     * @return String
     */
    public static String xmlOutputFormat(Document document,
            OutputFormat opFormat) {
        // 具有層次的格式輸出
        // OutputFormat format = OutputFormat.createPrettyPrint();
        // 緊湊的格式輸出
        // OutputFormat format = OutputFormat.createCompactFormat();
        StringWriter sw = new StringWriter();
        try {
            XMLWriter writer = new XMLWriter(opFormat);
            writer.setWriter(sw);
            writer.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

 

運行結果輸出如下:代碼 複製代碼 收藏代碼
  1. XML輸出格式定義Demo:   
  2. 轉換爲優雅層次的格式輸出:   
  3. <?xml version="1.0" encoding="UTF-8"?>   
  4.   
  5. <root>   
  6.   <info index="1" type="blog">   
  7.     <URL>http://sjsky.iteye.com</URL>   
  8.     <name id="sjsky">Michael</name>   
  9.     <categories>   
  10.       <category valule="java"/>   
  11.       <category valule="spring"/>   
  12.       <category valule="hibernate"/>   
  13.       <category valule="NoSQL"/>   
  14.       <category valule="MYSQL"/>   
  15.     </categories>   
  16.   </info>   
  17. </root>   
  18.   
  19. 轉換爲緊湊格式輸出:   
  20. <?xml version="1.0" encoding="UTF-8"?>   
  21. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>   
  22. DEMO End---------------------  

 

[六]、XML輸出文件:

 

Java代碼 複製代碼 收藏代碼
  1. /**  
  2.  * @blog http://sjsky.iteye.com  
  3.  * @author Michael  
  4.  * @param args  
  5.  */  
  6. public static void main(String[] args) {   
  7.     String xmlStr = "<root><info index=\"1\" type=\"blog\">"  
  8.             + "<URL>http://sjsky.iteye.com</URL>"  
  9.             + "<name id=\"sjsky\">Michael</name>"  
  10.             + "<categories><category valule=\"java\"/>"  
  11.             + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"  
  12.             + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"  
  13.             + "</categories></info></root>";   
  14.   
  15.     System.out.println("XML輸出文件:");   
  16.     String outFileName = "d:/test/michael/";   
  17.     try {   
  18.         Document document = DocumentHelper.parseText(xmlStr);   
  19.         xmlWriteXMLDoc(outFileName+"dom4j_info_out1.xml", document);   
  20.            
  21.         fileWriteXMLDoc(outFileName+"dom4j_info_out2.xml", document);   
  22.            
  23.     } catch (Exception e) {   
  24.         e.printStackTrace();   
  25.     }   
  26.   
  27.     System.out.println("DEMO End---------------------");   
  28. }   
  29.   
  30. /**  
  31.  *   
  32.  * @param fileName  
  33.  * @param document  
  34.  */  
  35. public static void xmlWriteXMLDoc(String fileName, Document document) {   
  36.     XMLWriter writer = null;   
  37.     try {   
  38.         //writer = new XMLWriter(new FileWriter(fileName));   
  39.         //writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createCompactFormat());   
  40.         writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createPrettyPrint());   
  41.         writer.write(document);   
  42.   
  43.     } catch (Exception e) {   
  44.         e.printStackTrace();   
  45.     } finally {   
  46.         try {   
  47.             if (null != writer) {   
  48.                 writer.close();   
  49.             }   
  50.         } catch (Exception e) {   
  51.             e.printStackTrace();   
  52.         }   
  53.     }   
  54. }   
  55.   
  56. /**  
  57.  *   
  58.  * @param fileName  
  59.  * @param document  
  60.  */  
  61. public static void fileWriteXMLDoc(String fileName, Document document) {   
  62.     FileWriter fw = null;   
  63.     try {   
  64.         fw = new FileWriter(fileName);   
  65.         document.write(fw);   
  66.     } catch (Exception e) {   
  67.         e.printStackTrace();   
  68.     } finally {   
  69.         try {   
  70.             if (null != fw) {   
  71.                 fw.close();   
  72.             }   
  73.         } catch (Exception e) {   
  74.             e.printStackTrace();   
  75.         }   
  76.     }   
  77. }  
    /**
     * @blog http://sjsky.iteye.com
     * @author Michael
     * @param args
     */
    public static void main(String[] args) {
        String xmlStr = "<root><info index=\"1\" type=\"blog\">"
                + "<URL>http://sjsky.iteye.com</URL>"
                + "<name id=\"sjsky\">Michael</name>"
                + "<categories><category valule=\"java\"/>"
                + "<category valule=\"spring\"/><category valule=\"hibernate\"/>"
                + "<category valule=\"NoSQL\"/><category valule=\"MYSQL\"/>"
                + "</categories></info></root>";

        System.out.println("XML輸出文件:");
        String outFileName = "d:/test/michael/";
        try {
            Document document = DocumentHelper.parseText(xmlStr);
            xmlWriteXMLDoc(outFileName+"dom4j_info_out1.xml", document);
            
            fileWriteXMLDoc(outFileName+"dom4j_info_out2.xml", document);
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("DEMO End---------------------");
    }

    /**
     * 
     * @param fileName
     * @param document
     */
    public static void xmlWriteXMLDoc(String fileName, Document document) {
        XMLWriter writer = null;
        try {
            //writer = new XMLWriter(new FileWriter(fileName));
            //writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createCompactFormat());
            writer = new XMLWriter(new FileWriter(fileName),OutputFormat.createPrettyPrint());
            writer.write(document);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != writer) {
                    writer.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param fileName
     * @param document
     */
    public static void fileWriteXMLDoc(String fileName, Document document) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(fileName);
            document.write(fw);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fw) {
                    fw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

生成的dom4j_info_out1.xml文件內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <root>  
  4.   <info index="1" type="blog">  
  5.     <URL>http://sjsky.iteye.com</URL>  
  6.     <name id="sjsky">Michael</name>  
  7.     <categories>  
  8.       <category valule="java"/>  
  9.       <category valule="spring"/>  
  10.       <category valule="hibernate"/>  
  11.       <category valule="NoSQL"/>  
  12.       <category valule="MYSQL"/>  
  13.     </categories>  
  14.   </info>  
  15. </root>  

 

生成的dom4j_info_out2.xml文件內容如下:

Xml代碼 複製代碼 收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <root><info index="1" type="blog"><URL>http://sjsky.iteye.com</URL><name id="sjsky">Michael</name><categories><category valule="java"/><category valule="spring"/><category valule="hibernate"/><category valule="NoSQL"/><category valule="MYSQL"/></categories></info></root>  

到此有關dom4j的簡單應用基本介紹完了,希望給新接觸的tx有所幫助。

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