最近有在項目中生成xml文件,但是生成之后的xml文件打開之后,是一坨,看起來真的不美觀,要是能夠格式化輸出來就好了。
這里說明一下,我使用DOM4J的方式生成的xml
public static void main(String[] args) { Document document = DocumentHelper.createDocument(); Element bookStore = document.addElement("bookStore"); Element book = bookStore.addElement("book"); book.addAttribute("category", "e-sport"); Element title = book.addElement("title"); title.addText("全職高手"); Element author = book.addElement("author"); author.addText("蝴蝶藍"); // 設置格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); File file = new File("D:\\圖紙\\books.xml"); XMLWriter writer = null; // 設置是否轉義 默認為true try { writer = new XMLWriter(new FileOutputStream(file), format); writer.setEscapeText(false); writer.write(document); writer.close(); } catch (IOException e) { System.out.println("生成文件的時候出現錯誤:"+e); } }
生成之后的文件打開之后就是格式化的
<?xml version="1.0" encoding="utf-8"?> <bookStore> <book category="e-sport"> <title>全職高手</title> <author>蝴蝶藍</author> </book> </bookStore>
參考網址;https://www.cnblogs.com/wenruo/p/6345122.html