


--使用OutputFormat.createPrettyPrint() 构造一个OutputFormat
--nwe XMLWriter(nwe FileWrite(File("文件名")),OutputFormat对象名);
OutputFormat of = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File("src/com/com/test/xml/domain/books2.xml")), of);
xmlWriter.write(document);
xmlWriter.close();
//1.通过DocumentHelper 的 createDocument方法 创建一个Document
Document document = DocumentHelper.createDocument();
//document.addElement("books").addElement("book").addAttribute("id","1");
//2.添加并得到根元素
Element books = document.addElement("books");
//3.为根节点添加子元素
Element book = books.addElement("book");
//4.为子元素添加属性
Element id = book.addAttribute("id", "1");
//5.为book的添加子节点
Element name = book.addElement("name");
Element author = book.addElement("author");
Element price = book.addElement("price");
//6.为book添加文本信息
name.addText("测试1");
author.addText("测试2");
price.addText("25.50");
/**
// 7.将doc输出到 books2.xml 文件中
Writer writer = new FileWriter(new File("src/com/com/test/xml/domain/books2.xml"));
document.write(writer);
//8.关闭资源
writer.close();
*/
//7.美化输出结构
OutputFormat of = OutputFormat.createPrettyPrint();
XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File("src/com/com/test/xml/domain/books2.xml")), of);
xmlWriter.write(document);
//8.关闭资源
xmlWriter.close(); 原文:https://www.cnblogs.com/zhuimu/p/14276502.html