使用 Transformer 制作的缩进 XML
我正在尝试从 Java 创建 XML,但遇到缩进问题。在下面的代码中你可以看到 OutputKeys.INDENT
设置为 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);
但它似乎没有影响,输出是:
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试设置 indent-amount,据我所知默认是 0。
Try to set indent-amount, AFAIK the default is 0.