我想将字符串格式化为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>
我希望每个新标记都以新行开头。
答案 0 :(得分:1)
OutputKeys.INDENT的精确效果未在规范中定义。但是,规范的XSLT 2.0版本是明确的,缩进必须仅在开始标记之前或在结束标记之后添加空格 - 换句话说,非空白文本节点的值永远不会被更改。
顺便说一下,在规范中也没有定义CDATA将在JAXP身份转换中保留,我对这种情况感到有些惊讶。