生成后的xml文件:
生成后的文件所在目录:
需要的jar包:
代码:
public static void main(String[] args) throws IOException {
//要生成xml文件,要准备各个节点,就是一个一个的Element元素对象
Document document = DocumentHelper.createDocument();
Element element = document.addElement("books");
Element book1 = element.addElement("book");
book1.addAttribute("id", "1");
Element ne1 = book1.addElement("name");
ne1.setText("西游记");
Element ae1 = book1.addElement("author");
ae1.setText("吴承恩");
Element book2 = element.addElement("book");
book2.addAttribute("id", "2");
Element ne2 = book2.addElement("name");
ne2.setText("水浒传");
Element ae2 = book2.addElement("author");
ae2.setText("施耐庵");
// 设置XML文档格式
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
// 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1
outputFormat.setEncoding("UTF-8");
//outputFormat.setSuppressDeclaration(true); //是否生产xml头
outputFormat.setIndent(true); //设置是否缩进
outputFormat.setIndent(" "); //以四个空格方式实现缩进
outputFormat.setNewlines(true); //设置是否换行
XMLWriter writer = new XMLWriter(new FileOutputStream(new File("bs.xml")),outputFormat);
writer.write(document);
}