如何在 Java 中漂亮地打印 XML 属性?
How to pretty print XML Attributes in Java?
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
tf.transform(new StreamSource(reader), new StreamResult(writer));
以上代码给出了以下结果:
<Response>
<Head>ERROR</Head>
<Body>
<ERROR code="1000" reason="ServerSOAPFaultException" description="Fault occurred while processing."/>
</Body>
</Response>
它不缩进 xml-属性,但我也需要缩进 xml-属性:
<Response>
<Head>ERROR</Head>
<Body>
<ERROR code="1000"
reason="ServerSOAPFaultException"
description="Fault occurred while processing."/>
</Body>
</Response>
怎么做?
使用 Saxon 序列化器而不是 Xalan 序列化器,如果您想要强制垂直堆叠属性,即使它们可以水平放置,请为 saxon:line-length 属性.
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
tf.transform(new StreamSource(reader), new StreamResult(writer));
以上代码给出了以下结果:
<Response>
<Head>ERROR</Head>
<Body>
<ERROR code="1000" reason="ServerSOAPFaultException" description="Fault occurred while processing."/>
</Body>
</Response>
它不缩进 xml-属性,但我也需要缩进 xml-属性:
<Response>
<Head>ERROR</Head>
<Body>
<ERROR code="1000"
reason="ServerSOAPFaultException"
description="Fault occurred while processing."/>
</Body>
</Response>
怎么做?
使用 Saxon 序列化器而不是 Xalan 序列化器,如果您想要强制垂直堆叠属性,即使它们可以水平放置,请为 saxon:line-length 属性.