生成後的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);
}