代码编写是参考这篇文档:
http://blog.csdn.net/lyjia2001/archive/2007/11/02/1862523.aspx
/**
* XmlOutput.java
* 2011-2-21 下午02:09:35
*/
package com.gbit.test;
import java.io.File;
import java.io.FileOutputStream;
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;
/**
* @author linzq
*
*/
public class XmlOutput
{
public static void main(String[] args) throws IOException
{
// 当前class文件所在的目录
String path = xmlOutput.class.getResource(".").getFile().toString();
// 利用DocumentHelper创建一个xml文档。
Document doc = DocumentHelper.createDocument();
// 用DocumentHelper创建的xml文档添加根元素。
Element root = doc.addElement("books");
// 添加子元素
Element author1 = root.addElement("author").addAttribute("name",
"james").addAttribute("location", "UK").addText(
"James Strachan");
Element author2 = root.addElement("author").addAttribute("name", "Bob")
.addAttribute("location", "USA").addText("Bob McWhirter");
FileOutputStream output = new FileOutputStream(new File(path +
"books_out.xml"));
// 格式化输出
OutputFormat format = OutputFormat.createPrettyPrint();
XMLWriter writer = new XMLWriter(output, format);
writer.write(doc);
writer.flush();
writer.close();
}
}
d