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

Him*_*ors 3 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>
Run Code Online (Sandbox Code Playgroud)

怎么会不起作用,我该怎么做呢?

Dim*_*hev 6

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

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

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

如果我们只将每个位置路径限制为元素名称,我们可以实现一个相当通用的动态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>
Run Code Online (Sandbox Code Playgroud)

当此转换应用于此XML文档时:

<root>
  <meta>
    <url_params>
      <param>
        <xxx>
          <value>5</value>
        </xxx>
      </param>
      <param>
        <yyy>
          <value>8</value>
        </yyy>
      </param>
    </url_params>
  </meta>
</root>
Run Code Online (Sandbox Code Playgroud)

产生了想要的正确结果:

root/meta/url_params/param/yyy/value: 8
Run Code Online (Sandbox Code Playgroud)


小智 5

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

因此,根据具体情况$inputid,您可以有不同的解决方案.

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

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

/root/meta/url_params/*[name()=$inputid]
Run Code Online (Sandbox Code Playgroud)

要么

/root/meta/url_params/*[@id=$inputid]
Run Code Online (Sandbox Code Playgroud)

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