My Spring Boot项目使用XML与Server通信。 (RESTful API)
我想在SpringBoot项目中记录相当格式化的xml数据(使用logback进行日志记录)
在Spring中记录相当格式化的xml的最佳方法是什么?
答案 0 :(得分:0)
你必须做这样的事情,我觉得它很好。使用sysout
更改我的log statement
。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class YourController{
.
.
.
.
public yourRestMethod() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputStream("Your XML")));
prettyPrint(doc);
}
public static final void prettyPrint(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
tf.transform(new DOMSource(xml), new StreamResult(out));
System.out.println(out.toString());
}
}