2012年3月20日 星期二

在 Java 中寫入 XML 檔案:使用 dom4j

dom4j 官方網站:http://dom4j.sourceforge.net/
在 Java 存取 XML 的方法好像有不少,會選 dom4j 是因為據說它效率還不錯,而且用法簡單!

以下直接舉一個寫入 XML 的例子
我是先建立一個 XMLConstructor 的 Class,然後在 main 去呼叫它~


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XMLConstructor {
  private Document document = null;
  private Element rootNodeElement = null;
  
  /**
   * Create XML document
   */
  public void createXmlDocument () {
    this.document = DocumentHelper.createDocument();
    this.document.setXMLEncoding("utf-8");
    this.rootNodeElement = this.document.addElement("root");
  }
  
  /**
   * Add an child node to root node.
   * @param tagName The name of the tag.
   * @param attr The value of attribute.
   * @param text The value of text.
   * @return The element of the new created node.
   */
  public Element addElement (String tagName, String attr, String text) {
    if(this.document == null)
      this.createXmlDocument();
    
    Element element = this.rootNodeElement.addElement(tagName);
    element.addAttribute("attribute", attr);
    element.setText(text);
    return element;
  }
  
  /**
   * Save the XML document to <code>storedFile</code> using UTF-8 encoding.
   * @param storedFile The stored file path.
   */
  public void saveToFile (File storedFile) {
    if(storedFile.exists())
      storedFile.delete();
    
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    XMLWriter writer = null;
    try {
      storedFile.createNewFile();
      
      OutputFormat format = OutputFormat.createPrettyPrint();  
            format.setEncoding("utf-8");
            fos = new FileOutputStream(storedFile);
            osw = new OutputStreamWriter(fos, Charset.forName("utf-8"));
      writer = new XMLWriter(osw, format);
      writer.write(this.document);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if(writer != null) writer.close();
        if(osw != null) osw.close();
        if(fos != null) fos.close();
      } catch (IOException e) {}
    }
  }
}

main 的地方呼叫方法很簡單

public static void main(String[] args) {
  XMLConstructor xml = new XMLConstructor();
  xml.createXmlDocument();
  // Create two nodes with tag 'element'
  xml.addElement("element", "attribute1", "text_a_b_c");
  xml.addElement("element", "attribute2", "text_d_e_f");
  // Store the xml document to a file
  xml.saveToFile(new File("D:\\home\\text.xml"));
}

最後產生的檔案:

<?xml version="1.0" encoding="utf-8"?>

<root>
  <element attribute="attribute1">text_a_b_c</element>
  <element attribute="attribute2">text_d_e_f</element>
</root>

沒有留言: