与使用 XML Spy 进行测试相比,在将 XSLT 与 Java 程序应用时,我看到不一致的行为。具体来说,在使用 Java 时,该xsl:for-each
指令似乎不会遍历整个列表。在使用 XML Spy 进行测试时,情况并非如此。
我的 XML 文档:
<metadata xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<maps>
<geographicCoverages>
<coverage key="ON">Ontario</coverage>
<coverage key="MB">Manitoba</coverage>
<coverage key="SK">Saskatchewan</coverage>
<coverage key="AB">Alberta</coverage>
<coverage key="BC">British Columbia</coverage>
<coverage key="YT">Yukon</coverage>
<coverage key="NU">Nunavut</coverage>
</geographicCoverages>
</maps>
<entry>
<string>GEO_COVERAGE</string>
<list>
<string>BC</string>
<string>ON</string>
</list>
</entry>
...
</metadata>
我的 XSLT:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
<xsl:output method="text" version="1.0" indent="yes"/>
<xsl:key name="geoCoverageKey" match="metadata/maps/geographicCoverages/coverage" use="@key" />
<xsl:template match="/metadata">
<xsl:for-each select="entry[string='GEO_COVERAGE']/list">
<xsl:value-of select="key('geoCoverageKey', string)" separator=", " />
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
当我使用 XMLSpy 测试上述 XSLT 时,我得到了预期的输出:
Ontario, British Columbia
我的 Java 测试程序:
public static void main(String[] args) throws TransformerException {
String xsltPath = "test_migration.xslt";
String xmlPath = "test-migration.xml";
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xsltPath));
StreamResult result = new StreamResult( new StringWriter() );
transformer.transform(new StreamSource(xmlPath), result );
System.out.println( result.getWriter().toString() );
}
但是,当我运行上面的 Java 测试程序时,我得到的输出只包含一个值;安大略省。我不知道为什么我会得到这种差异。