如何从Java中打印XML?

本文翻译自: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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值