如何在Java中打印XML属性?

时间:2017-02-25 04:49:17

标签: java xml pretty-print xml-attribute

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-attributes,但我还需要缩进xml-attributes:

<Response>
    <Head>ERROR</Head>
    <Body>
        <ERROR code="1000"
               reason="ServerSOAPFaultException"
               description="Fault occurred while processing."/>
    </Body>
</Response>

怎么做?

1 个答案:

答案 0 :(得分:2)

使用Saxon序列化程序而不是Xalan序列化程序,如果要强制属性垂直堆叠,即使它们适合水平放置,也要为saxon:line-length属性设置一个小值。