怎樣將生成的xml檔案進行格式化
阿新 • • 發佈:2021-08-10
最近有在專案中生成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