package com.beckham.dom; 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; /** * @author 作者<Beckham> * Email:gaowm0207@gmail.com * Jan 28, 2010 10:03:12 AM * DOM4j写XML文件 */ public class CreateXMLFile { public static void main(String[] args)throws Exception { createFile("src/com/beckham/dom/application.xml") ; } public static void createFile(String fileName) throws Exception{ Document document = DocumentHelper.createDocument() ; //根节点 Element root = document.addElement("beans") ; //根节点注释 root.addComment("这是根节点") ; //第一个子节点 Element elementBean1 = root.addElement("bean") ; elementBean1.addAttribute("id", "boy") ; elementBean1.addAttribute("class", "com.beckham.spring.Boy") ; Element elementProp = elementBean1.addElement("property") ; elementProp.addAttribute("name", "user") ; elementProp.addAttribute("ref", "com.beckham.User") ; //第二个子节点 Element elementBean2 = root.addElement("bean") ; elementBean2.addAttribute("id", "girl") ; elementBean2.addAttribute("class", "com.beckham.spring.Girl") ; Element elementProp2 = elementBean2.addElement("property") ; elementProp2.addAttribute("name", "user") ; elementProp2.addAttribute("ref", "com.beckham.User") ; //前一个参数表示缩进4个空格 OutputFormat format = new OutputFormat(" ",true) ; format.setEncoding("GBK") ; XMLWriter w = new XMLWriter(new FileWriter(new File(fileName)),format ) ; w.write(document) ; w.close() ; } } <?xml version="1.0" encoding="GBK"?> <beans> <!--这是根节点--> <bean id="boy" class="com.beckham.spring.Boy"> <property name="user" ref="com.beckham.User"/> </bean> <bean id="girl" class="com.beckham.spring.Girl"> <property name="user" ref="com.beckham.User"/> </bean> </beans>