用Transformer缩进XML文本 [英] indent XML text with Transformer

查看:140
本文介绍了用Transformer缩进XML文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Source source = new DOMSource(rootElement); 
结果结果=新的StreamResult(xmlFile);
变压器变压器= TransformerFactory.newInstance()。newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT,yes);
transformer.transform(source,result);

这是输出文件:

 <?xml version =1.0encoding =UTF-8?> 
< feature-sequences>
< sequence>
<初始帧> 0< /初始帧>
< points>
< point>
< x> 274.0< / x>
< y> 316.0< / y>
< / point>
...

我希望这个文件被缩进,例如:

 <?xml version =1.0encoding =UTF-8?> 
< feature-sequences>
< sequence>
<初始帧> 0< /初始帧>
< points>
< point>
< x> 274.0< / x>
< y> 316.0< / y>
< / point>
...

调用 setOutputProperty 在我的代码没有解决问题,它实际上使新文本行(但不缩进)。

任何人有一个解决方案,没有是否需要外部库?

解决方案

您可能必须指定要缩进的空格数量。 b
$ b

  transformer.setOutputProperty({http://xml.apache.org/xslt}indent-amount,4); 


I'm writing an XML file with the following code:

Source source = new DOMSource(rootElement);
Result result = new StreamResult(xmlFile);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);

and this is the output file:

<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
<sequence>
<initial-frame>0</initial-frame>
<points>
<point>
<x>274.0</x>
<y>316.0</y>
</point>
...

I want this file to be indented, for example:

<?xml version="1.0" encoding="UTF-8"?>
<feature-sequences>
  <sequence>
    <initial-frame>0</initial-frame>
    <points>
      <point>
        <x>274.0</x>
        <y>316.0</y>
      </point>
...

the call to setOutputProperty in my code doesn't solve the problem, it actually makes the text with new lines (but not indented).

anyone has a solution to this, without the need of external libraries?

解决方案

You may have to specify the amount of spaces to indent as well:

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

这篇关于用Transformer缩进XML文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆