转自:
下文讲述使用dom4j生成XML文件的方法分享,如下所示:
1.创建一个文档模型
Document document = DocumentHelper.createDocument();
2.创建元素的根节点
Element root = document.addElement("root");
3.根节点添加元素和属性
root.addElement("author").addAttribute("name","maomao").addAttribute("location","CN").addText("shenzhen" );
4.保存文件
writer.write(document);
writer.close();
例:
public static void main(String[] args) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter("test.xml"), format); Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); root.addComment("This is xml comment"); root.addElement("author").addAttribute("name", "maomao").addAttribute("location", "CN").addText("shenzhen"); writer.write(document); writer.close(); }