Java format xml using Transformer with CDATA part

做~自己de王妃 提交于 2019-12-13 06:15:37

问题


I want to format string to xml this my code:

Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(4));
transformer.transform(xmlInput, xmlOutput);

This is my String

 <a><attr name="a1">this is a test</attr><attr name="a2"><![CDATA[this is a test inside cdata part]]></attr></a>

Output

<?xml version="1.0" encoding="UTF-8"?>
<a>
    <attr name="a1">this is a test</attr>
    <attr name="a2"><![CDATA[this is a test inside cdata part]]></attr>
</a>

desired

<?xml version="1.0" encoding="UTF-8"?>
<a>
    <attr name="a1">
        this is a test
    </attr>
    <attr name="a2">
        <![CDATA[this is a test inside cdata part]]>
    </attr>
</a>

I want each new tag will start in new line.


回答1:


The precise effect of OutputKeys.INDENT is not defined in the specifications. The XSLT 2.0 version of the spec, however, is explicit that indentation must add whitespace only before a start tag or after an end tag - in other words, the value of a non-whitespace text node will never be changed.

Incidentally, it's also not defined in the spec that CDATA will be preserved in a JAXP identity transformation, and I'm slightly surprised that this happens.



来源:https://stackoverflow.com/questions/11384238/java-format-xml-using-transformer-with-cdata-part

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