在 XSLT 中,为什么我无法使用 xsl:attribute 设置 value-of 的 select-attribute,有什么好的选择? [英] In XSLT, how come I can't set the select-attribute of a value-of using xsl:attribute, and what's a good alternative?

查看:25
本文介绍了在 XSLT 中,为什么我无法使用 xsl:attribute 设置 value-of 的 select-attribute,有什么好的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常量和一个变量,我想把它们放在一起来选择一个特定的节点,这就是我想要做的:

I have a constant and a variable that I wann mouch together to select a specific node, this is what I want to do:

<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>

为什么它不起作用,我该怎么办?

How come it doesn't work, and what could I do instad?

推荐答案

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

While @Alejandro is right that in the general case dynamic evaluation will be needed (and this may be provided in XSLT 2.1+), there are manageable simpler cases.

例如,如果 $inputid 只包含一个名字,你可能想要这个:

For example, if $inputid contains just a name, you probably want this:

<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

这篇关于在 XSLT 中,为什么我无法使用 xsl:attribute 设置 value-of 的 select-attribute,有什么好的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆