使用Transformer缩进XML

使用Transformer缩进XML

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

问题描述

我尝试从Java创建XML,并遇到缩进问题。在下面的代码中,可以看到 OutputKeys.INDENT 设置为 ...

  //设置一个变换器
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,yes);
trans.setOutputProperty(OutputKeys.INDENT,yes);

//从xml树创建字符串
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source,result);
String xmlString = sw.toString();

//打印xml
System.out.println(xmlString);

但似乎没有影响,输出是:

 < dataset id =1>< br> 
<路径>< /路径>< br>
< session id =1>< br>
< method>< br>
< timestamp>时间戳< /时间戳>< br>
< signiture>< br>
< classPath>< / classPath>< br>
<名称> methodName< /名称>< br>
< declarationType> String< / declarationType>< br>
<参数>< br>
< parameter> String< / parameter>< br>
< parameter> int< / parameter>< br>
< /参数>< br>
< / signiture>< br>
<参数>< br>
<参数> SomeValue< /参数>< br>
< argument> AnotherValue< / argument>< br>
< /参数>< br>
< return> ReturnValue< / return>< br>
< / method>< br>
< / session>< br>
< / dataset>< br>


解决方案

尝试设置缩进量,AFAIK默认为0。

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


I am trying to create XML from Java and am having problems with indenting. In the following code you can see OutputKeys.INDENT set to yes...

        //set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();

        //print xml
        System.out.println(xmlString);

but it seems to have no affect, the output is:

<dataset id="1"><br>
<path></path><br>
<session id="1"><br>
<method><br>
<timestamp>a timestamp</timestamp><br>
<signiture><br>
<classPath></classPath><br>
<name>methodName</name><br>
<declarationType>String</declarationType><br>
<parameters><br>
<parameter>String</parameter><br>
<parameter>int</parameter><br>
</parameters><br>
</signiture><br>
<arguments><br>
<argument>SomeValue</argument><br>
<argument>AnotherValue</argument><br>
</arguments><br>
<return>ReturnValue</return><br>
</method><br>
</session><br>
</dataset><br>
解决方案

Try to set indent-amount, AFAIK the default is 0.

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

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

08-18 09:18