XSLT2 中变量的 Select Child

Select Child of a Variable in XSLT2

我正在尝试使用此 XSLT2 脚本 select 变量的 child 节点:

<?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>,因此 child selection i错了。

我怎样才能让它工作,以便我得到 <out>car<out>

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>