2017-02-25 106 views
0
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)); 

上面的代码给我下面的结果:如何在Java中漂亮地打印XML属性?

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

如何做它?

回答

2

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

+0

你能提供一个示例代码吗? –

+0

Saxon支持JAXP接口,因此您可以使用已有的代码 - 只需将Saxon放在类路径中即可。 –

+0

我已将[Saxon-HE依赖项](https://mvnrepository.com/artifact/net.sf.saxon/Saxon-HE/9.7.0-15)添加到我的项目中,并开始缩进属性,但它只起作用对于包含许多属性的元素,对于仅包含3-4个属性的元素不起作用。你能解释一下如何为saxon:line-length属性设置一个小值吗? –