Search code examples
javaxmlpretty-printxml-attribute

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));

the above code gives me the following result:

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

it does not indent xml-attributes, but I need xml-attributes to be indented as well:

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

How to do it?


Solution

  • Use the Saxon serializer rather than the Xalan serializer, and if you want to force attributes to be stacked vertically even when they would fit horizontally, set a small value for the saxon:line-length property.