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);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
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);
}
code smippet for formatting xml
最新推荐文章于 2024-01-25 08:27:25 发布
本文介绍了一个用于美化XML格式的实用工具。该工具通过输入原始XML字符串,并指定缩进空格数量来格式化输出易读的XML结构。文章提供了两个方法:一个是默认使用2个空格进行缩进的通用美化方法;另一个允许用户自定义缩进数量。
22万+

被折叠的 条评论
为什么被折叠?



