2017-02-25 107 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屬性設置一個小值嗎? –