package com.bjpowernodetest;import java.io.FileWriter;import java.io.IOException;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;import junit.framework.TestCase;/** * * @author Kevin * 建立XML文檔並儲存到磁碟檔案中(GBK) */public class TestXMLWriter extends TestCase {/**<?xml version="1.0" encoding="UTF-8"?> <items> <item> <id>10003</id> <name>保定</name> </item> <item> <id>10004</id> <name>天津</name> </item> </items> *//** * 建立上述的XML */public void testXMLWriter() {// 建立XML文檔樹Document document = DocumentHelper.createDocument();// 建立根節點itemsElement itemsElement = document.addElement("items");// 建立根節點下的item子節點Element itemElement = itemsElement.addElement("item");// item節點有兩個子節點Element idElement = itemElement.addElement("id");idElement.setText("10003");Element nameElement = itemElement.addElement("name");nameElement.setText("保定");// 設定XML文檔格式,漂亮的格式OutputFormat outputFormat = OutputFormat.createPrettyPrint();// 設定XML編碼方式,即是用指定的編碼方式儲存XML文檔到檔案,並讓瀏覽器用指定的編碼方式解析XML文檔outputFormat.setEncoding("GBK");try {// xmlWriter對應磁碟的一個檔案(Test.xml),此處(GBK編碼)要用FileWriter,否則可能導致亂碼,比如用FileOutputStream,會導致亂碼XMLWriter xmlWriter = new XMLWriter(new FileWriter("C:/Test.xml"), outputFormat);// 把建立好的XML文檔寫入檔案xmlWriter.write(document);xmlWriter.close();System.out.println("把XML文檔寫入檔案成功!");} catch (IOException e) {e.printStackTrace();throw new RuntimeException("把XML文檔寫入檔案失敗!");}}}