【问题标题】:Use a variable in XSLT select在 XSLT 选择中使用变量
【发布时间】:2014-08-18 03:51:51
【问题描述】:

我正在尝试创建一个命名模板或函数,其中我传递一个节点名称,它将选择它作为 xpath 表达式的最后一级。但它返回的只是我作为参数传入的字符串。在下面的示例中,返回的值为“name”

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output indent="yes"></xsl:output>

    <xsl:template name="get-prefered">
        <xsl:param name="field-name"/> 

        <xsl:variable name="vCondition" select="name"/>
        <xsl:variable name="x" select="sources/source[@type='C']/$field-name"/>
        <xsl:value-of select="$x"></xsl:value-of>
    </xsl:template>

    <xsl:template match="/">
        <xsl:call-template name="get-prefered">
            <xsl:with-param name="field-name">name</xsl:with-param>
        </xsl:call-template>
        </xsl:template>
</xsl:stylesheet>

输入 XML:

<?xml version="1.0" encoding="UTF-8"?>
<sources>
    <source type='C'>
        <name>Joe</name>
        <age>10</age>
    </source>
    <source type='B'>
        <name>Mark</name>
        <age>20</age>
    </source>
</sources>

【问题讨论】:

    标签: xml xslt xslt-2.0


    【解决方案1】:

    改变

    <xsl:variable name="x" select="sources/source[@type='C']/$field-name"/>
    

    <xsl:variable name="x" select="sources/source[@type='C']/*[name()=$field-name]"/>
    

    它返回:

    Joe
    

    【讨论】:

      【解决方案2】:

      这里的问题:

      select="sources/source[@type='C']/$field-name"
      

      是变量$field-name包含一个字符串,而不是一个位置路径——所以表达式扩展为:

      select="sources/source[@type='C']/'name'"
      

      如果您使用的是 XSLT 2.0 处理器,那么您很可能可以访问可以将字符串转换为路径的 evaluate() 函数,例如http://www.saxonica.com/documentation9.4-demo/html/extensions/functions/evaluate.html 否则,您将需要使用其他方法 - 例如,Joel M. Lamsen 在他的回答中显示的方法。

      【讨论】:

      【解决方案3】:

      我假设你的命名模板要处理整个文档,那么xslt是这样的……

      <xsl:output indent="yes"></xsl:output>
      
      <xsl:template name="get-prefered">
          <xsl:param name="field-name"/> 
      
          <xsl:variable name="vCondition" select="$field-name/name"/>
          <xsl:variable name="x" select="$field-name/sources/source[@type='C']/name"/>
          <xsl:value-of select="$x"></xsl:value-of>
      </xsl:template>
      
      <xsl:template match="/">
          <xsl:call-template name="get-prefered">
              <xsl:with-param name="field-name" select="."></xsl:with-param>
          </xsl:call-template>
          </xsl:template>
      

      【讨论】:

      • 不完全是。我希望能够在 xpath 的最后一级传递(在这个简化的示例中,唯一有效的选择是姓名和年龄)并返回一个值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      相关资源
      最近更新 更多