import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class TEXT01 { public static void main(String[] args) throws Exception { //1,生成DOM树 Document doc = DocumentHelper.createDocument(); Element email = doc.addElement("email"); email.addAttribute("date","2018-5-5"); email.addAttribute("time","9:49:19"); email.addElement("form").setText("aaa@aaa.com"); Element to = email.addElement("to"); to.addElement("to-email").setText("bbb@bbb.com"); to.addElement("to-email").setText("ccc@ccc.com"); to.addElement("to-email").setText("ddd@ddd.com"); email.addElement("subject").setText(""); Element body = email.addElement("body"); body.setText(">>>Hello Dom4j!!!<<<"); body.addCDATA(">>>你哈渐渐<<<"); //2,吧dom树输出XML //流 FileOutputStream out = new FileOutputStream("d:/e.xml"); //格式工具 OutputFormat fmt = // OutputFormat.createCompactFormat(); OutputFormat.createPrettyPrint(); fmt.setEncoding("UTF-8"); //xml输出工具 XMLWriter write = new XMLWriter(out,fmt); write.write(doc); write.flush(); write.close(); } }