如何从Java中很好地打印XML?我有一个包含XML的Java字符串,没有行提要或缩进。我想将它转换为格式良好的XML字符串。我该怎么做?String unformattedXml = "<tag><nested>hello</nested></tag>";String formattedXml = new [UnknownClass]().format(unformattedXml);注意:我的输入是弦..我的输出是弦.(基本)模拟结果:<?xml version="1.0" encoding="UTF-8"?><root>
<tag>
<nested>hello</nested>
</tag></root>
3 回答
撒科打诨
TA贡献1934条经验 获得超2个赞
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}}public static String prettyFormat(String input) {
return prettyFormat(input, 2);}prettyFormat("<root><child>aaa</child><child/></root>");<?xml version="1.0" encoding="UTF-8"?><root> <child>aaa</child> <child/></root>
添加回答
举报
0/150
提交
取消
