我需要将 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>
谁能帮助我错过了什么?