2012-12-04 45 views
0

我需要將xml文檔轉換爲另一種格式。爲此,我使用Transformer對象中的構建。此外,我想在相同的步驟內打印出結果,但我總是得到一個醜陋的平面XML文件。漂亮的打印不適用於xsl轉換

這裏是我寫的代碼:

private static void transformXML(File source, File destination, URL xslt) throws IOException, TransformerException { 
    final FileOutputStream fos = new FileOutputStream(destination); 
    try { 
     final Source legacySource = new StreamSource(source); 
     final InputStream in = xslt.openStream(); 
     try { 
      final Source sourceApp = new StreamSource(in); 
      final TransformerFactory transFact = TransformerFactory.newInstance(); 
      transFact.setAttribute("indent-number", 2); 
      final Transformer t = transFact.newTransformer(sourceApp); 
      t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); 
      t.setOutputProperty(OutputKeys.METHOD, "xml"); 
      t.setOutputProperty(OutputKeys.INDENT, "yes"); 
      t.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-15"); 
      t.transform(legacySource, new StreamResult(new OutputStreamWriter(fos, "ISO-8859-15"))); 
      // t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); 
     } finally { 
      in.close(); 
     } 
    } finally { 
     fos.close(); 
    } 
} 

結果並八方通樣子:

<?xml version="1.0" encoding="ISO-8859-15"?><application xsi:noNamespaceSchemaLocation="essential-config.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<application-settings> 
<gui-mode>true</gui-mode> 
<db-config>false</db-config> 
<application-mode>mode</application-mode> 
... 
</application-settings> 
... 
</application> 

這裏是XSL我使用

<?xml version="1.0" ?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" version="1.0" encoding="ISO-8859-15" indent="yes"/> 
    <xsl:template match="/"> 
     <application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="essential-config.xsd"> 
       <application-settings> 
        <gui-mode><xsl:value-of select="configuration/general/gui-mode" /></gui-mode> 
        <db-config>false</db-config> 
        <application-mode><xsl:value-of select="configuration/general/application-mode" /></application-mode> 
        <process-id><xsl:value-of select="configuration/general/process-id" /></process-id> 
        <host><xsl:value-of select="configuration/translog/host" /></host> 
        <sml-client-id><xsl:value-of select="configuration/general/sml-client-id" /></sml-client-id> 
        <company-id><xsl:value-of select="configuration/general/companyId" /></company-id> 
       </application-settings> 
       <xsl:copy-of select="configuration/database" /> 
     </application> 
</xsl:template> 

任何人都可以幫助你我錯過了嗎?

+0

什麼是'在樣式表'標籤? –

+0

@JimGarrison標籤看起來像' – sebastian

+0

您將不得不張貼XSL –

回答

0

試試這個:

t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); 
+0

謝謝你的回答。我已經嘗試過這一點,但它以相同的結果結束。 – sebastian