本文翻译自:How to pretty print XML from Java?
I have a Java String that contains XML, with no line feeds or indentations. 我有一个包含XML的Java字符串,没有换行符或缩进。 I would like to turn it into a String with nicely formatted XML. 我想把它变成一个格式很好的XML的字符串。 How do I do this? 我该怎么做呢?
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
Note: My input is a String . 注意:我的输入是一个字符串 。 My output is a String . 我的输出是一个字符串 。
(Basic) mock result: (基本)模拟结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
#1楼
参考:https://stackoom.com/question/aBA/如何从Java中打印XML
#2楼
I have found that in Java 1.6.0_32 the normal method to pretty print an XML string (using a Transformer with a null or identity xslt) does not behave as I would like if tags are merely separated by whitespace, as opposed to having no separating text. 我发现在Java 1.6.0_32中,相当于打印XML 字符串 (使用带有null或身份xslt的Transformer)的常规方法,如果标签仅由空格分隔,则表现不像我想要的那样,而不是没有分隔文本。 I tried using <xsl:strip-space elements="*"/>
in my template to no avail. 我尝试在我的模板中使用<xsl:strip-space elements="*"/>
无效。 The simplest solution I found was to strip the space the way I wanted using a SAXSource and XML filter. 我发现最简单的解决方案是使用SAXSource和XML过滤器以我想要的方式剥离空间。 Since my solution was for logging I also extended this to work with incomplete XML fragments. 由于我的解决方案是用于日志记录,我还将其扩展为使用不完整的XML片段。 Note the normal method seems to work fine if you use a DOMSource but I did not want to use this because of the incompleteness and memory overhead. 请注意,如果使用DOMSource,正常方法似乎工作正常,但由于不完整性和内存开销,我不想使用它。
public static class WhitespaceIgnoreFilter extends XMLFilterImpl
{
@Override
public void ignor