漂亮的打印不适用于xsl转换

时间:2012-12-04 06:59:17

标签: java xml xslt pretty-print

我需要将xml文档转换为另一种格式。为此,我正在使用Transformer对象中的构建。另外我想在同一步骤中打印结果,但我总是得到一个丑陋的扁平xml文件。

这是我写的代码:

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>

任何人都可以帮助我错过的东西吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

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