摘要:寫入XML 檔案:使用dom4j
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) {} } } }
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>