Indent XML made with Transformer [duplicate]

懵懂的女人 提交于 2019-12-23 12:37:59

问题


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>

回答1:


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

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



回答2:


Document doc;

.....

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new File("filename.xml")));
transformer.transform(new DOMSource(doc), new StreamResult(System.out));


来源:https://stackoverflow.com/questions/5749217/indent-xml-made-with-transformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!