在XSLT2中选择变量的子项

时间:2015-09-03 08:33:58

标签: variables xslt java-7 xslt-2.0 xalan

我正在尝试使用此XSLT2脚本选择变量的子节点:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:param name="lang">en</xsl:param>

  <xsl:variable name="text">
    <xsl:choose>
      <xsl:when test="$lang='en'">
        <car>car</car>
        <bike>bike</bike>
      </xsl:when>
      <xsl:when test="$lang='de'">
        <car>Auto</car>
        <bike>Fahrrad</bike>
      </xsl:when>
    </xsl:choose>
  </xsl:variable>

  <xsl:template match="/foo">
    <out>
      <xsl:value-of select="$text/car"/>
    </out>
  </xsl:template>
</xsl:stylesheet>

当我使用Java 7执行它时,我收到以下错误消息:

10:23:29,682 INFO  [main] Main  - launchFile: C:\Users\chris\workspace\.metadata\.plugins\org.eclipse.wst.xsl.jaxp.launching\launch\launch.xml
10:23:29,760 ERROR [main] JAXPSAXProcessorInvoker  - Could not compile stylesheet
10:23:29,760 ERROR [main] JAXPSAXProcessorInvoker  - Error checking type of the expression 'FilterParentPath(variable-ref(text/result-tree), step("child", 15))'.
javax.xml.transform.TransformerConfigurationException: Error checking type of the expression 'FilterParentPath(variable-ref(text/result-tree), step("child", 15))'.
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:989)

当我将select$text/car更改为$text时,我得到<out>carbike</out>,因此我选择了儿童选择错误。

如何让它工作,以便我得到<out>car<out>

1 个答案:

答案 0 :(得分:3)

Xalan不支持XSLT-2.0。例如,您应该切换到Saxon

如果您完全使用Xalan XSL-T处理器,则可以使用XSL-T扩展以这种方式重构样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">
    <xsl:param name="lang">en</xsl:param>

    <xsl:variable name="text">
        <xsl:choose>
            <xsl:when test="$lang='en'">
                <car>car</car>
                <bike>bike</bike>
            </xsl:when>
            <xsl:when test="$lang='de'">
                <car>Auto</car>
                <bike>Fahrrad</bike>
            </xsl:when>
        </xsl:choose>
    </xsl:variable>

    <xsl:template match="/foo">
        <out>
            <xsl:value-of select="exsl:node-set($text)/car"></xsl:value-of>
        </out>
    </xsl:template>
</xsl:stylesheet>