我想将字符串格式化为 xml 这是我的代码:
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);
这是我的字符串
<a><attr name="a1">this is a test</attr><attr name="a2"><![CDATA[this is a test inside cdata part]]></attr></a>
输出
<?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>
想要的
<?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>
我希望每个新标签都以新行开始。