大家好,又见面了,我是你们的朋友全栈君。
最近有在项目中生成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
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/154681.html原文链接:https://javaforall.cn