在XSLT中,为什么我不能使用xsl:attribute设置value-of的select-attribute,什么是一个好的选择呢?

时间:2010-08-20 12:13:07

标签: xslt xpath

我有一个常量和变量,我想要一起选择一个特定的节点,这就是我想做的事情:

<xsl:attribute name="value">
 <xsl:value-of>
  <xsl:attribute name="select">
   <xsl:text>/root/meta/url_params/
   <xsl:value-of select="$inputid" />
  </xsl:attribute>
 </xsl:value-of>
</xsl:attribute>

为什么它不起作用,我能做什么instad?

2 个答案:

答案 0 :(得分:6)

虽然@Alejandro是正确的,但在一般情况下需要进行动态评估(这可能在XSLT 2.1+中提供),但是有一些可管理的简单案例。

例如,如果$inputid只包含一个名称,您可能需要

<xsl:value-of select="/root/meta/url_params/*[name()=$inputid]"/>

如果我们只将每个位置路径限制为元素名称,我们可以实现一个相当通用的动态XPath求值程序:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:param name="inputId" select="'param/yyy/value'"/>

 <xsl:variable name="vXpathExpression"
  select="concat('root/meta/url_params/', $inputId)"/>

 <xsl:template match="/">
  <xsl:value-of select="$vXpathExpression"/>: <xsl:text/>

  <xsl:call-template name="getNodeValue">
    <xsl:with-param name="pExpression"
         select="$vXpathExpression"/>
  </xsl:call-template>
 </xsl:template>

 <xsl:template name="getNodeValue">
   <xsl:param name="pExpression"/>
   <xsl:param name="pCurrentNode" select="."/>

   <xsl:choose>
    <xsl:when test="not(contains($pExpression, '/'))">
      <xsl:value-of select="$pCurrentNode/*[name()=$pExpression]"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="getNodeValue">
        <xsl:with-param name="pExpression"
          select="substring-after($pExpression, '/')"/>
        <xsl:with-param name="pCurrentNode" select=
        "$pCurrentNode/*[name()=substring-before($pExpression, '/')]"/>
      </xsl:call-template>
    </xsl:otherwise>
   </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

在此XML文档上应用此转换时

<root>
  <meta>
    <url_params>
      <param>
        <xxx>
          <value>5</value>
        </xxx>
      </param>
      <param>
        <yyy>
          <value>8</value>
        </yyy>
      </param>
    </url_params>
  </meta>
</root>

产生了想要的正确结果

root/meta/url_params/param/yyy/value: 8

答案 1 :(得分:5)

标准XSLT 1.0中没有针对XPath表达式的运行时评估

因此,根据$inputid,你可以有不同的解决方案。

但是这个/root/meta/url_params/$inputid是错误的,因为/的右手必须是XPath 1.0中的相对路径(在XPath 2.0中也可以是函数调用)。

对于特殊情况,您可以使用:

/root/meta/url_params/*[name()=$inputid]

/root/meta/url_params/*[@id=$inputid]

对于一般情况,我会像Dimitre的答案那样使用walker模式。