日期:2014-05-20 浏览次数:20678 次
package com.zjm.xml; import java.io.File; import java.io.FileWriter; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class createXML { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub createXML xml = new createXML(); xml.create(); } public boolean create() { boolean flag = false; Document document = null; //文档 Element books = null; //根节点 Element book = null; //book节点 Element text = null; //text节点 OutputFormat format = null; XMLWriter writer = null; try { document = DocumentHelper.createDocument(); books = document.addElement("books"); books.addComment("注释"); book = books.addElement("book"); book.addAttribute("name", "book1"); book.addAttribute("show", "true"); text = book.addElement("text"); text.setText("text1"); book = books.addElement("book"); book.addAttribute("name", "book2"); book.addAttribute("show", "false"); text = book.addElement("text"); text.setText("text2"); format = OutputFormat.createPrettyPrint(); format.setEncoding("GBK"); //format.setEncoding("UTF-8"); //用utf-8也不行 System.out.println(document.asXML()); writer = new XMLWriter(new FileWriter(new File("E://mytext.xml")), format); writer.write(document); writer.close(); flag = true; return flag; } catch(Exception e) { e.printStackTrace(); } return flag; } }
<?xml version="1.0" encoding="GBK"?> <books> <!--??--> <book name="book1" show="true"> <text>text1</text> </book> <book name="book2" show="false"> <text>text2</text> </book> </books>