使用dom4j的自带的OutputFormat
package com.wings.util;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.IOException;
import java.io.StringWriter;
public class OutputUitl {
public static String getPrettyXml(Document document) {
String s = null;
XMLWriter writer = null;
try {
StringWriter stringWriter = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setSuppressDeclaration(false); // 带<?xml version="1.0" encoding="UTF-8"?>
format.setIndent(" "); // 空格占位符
format.setIndentSize(3); // 缩进长度
format.setNewlines(true); // 换行
format.setNewLineAfterDeclaration(false); // 头部定义后面不开始新行
writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
s = stringWriter.getBuffer().toString();
} catch (IOException var) {
var.printStackTrace();
}finally {
if (writer != null)
{
try {
writer.close();
} catch (IOException var) {
var.printStackTrace();
}
}
}
return s;
}
}
输出后格式如下:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<no>{K3BsHjson}</no>
<key>Y3VC5</key>
<cardno>6212268533289894396</cardno>
<dtype>json</dtype>
<productNo/>
<bizType/>
<payee_acct_no/>
<payee_acct_name/>
</xml>