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.
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.