xslt测试一组节点的值是否相等

时间:2013-02-04 02:35:02

标签: xslt

给出以下xml:

<parameterGroup>
    <parameter value="1" name="Level0_stratum">
    </parameter>
    <parameter value="1" name="Level2_stratum">
    </parameter>
    <parameter value="1" name="Level1_stratum">
    </parameter>
    <parameter value="6" name="foo">
    </parameter>       
    <parameter value="9" name="bar">
    </parameter>    
</parameterGroup>

我想派生一个布尔变量,指示所有Level * _stratum值的@value是否相同,在这种情况下它们是(1)。

到目前为止,我已经能够按如下方式对一组中的所有相关节点进行分组:

select="//parameter[starts-with(@name,'Level') and ends-with(@name,'_stratum') ]"

但是我不确定比较所有@value属性的最有效方法是否相等?

2 个答案:

答案 0 :(得分:2)

如果ends-with()可用,那么你正在使用XSLT 2.0,因此distinct-values()可用,所以你可以简单地做到

count(distinct-values(
  //parameter[starts-with(@name,'Level') and ends-with(@name,'_stratum') ])/@value))
= 1

答案 1 :(得分:1)

我相信这应该做你想要做的事情(value-of行不是必需的,只是在那里显示变量的值):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <xsl:variable 
             name="allStrata"
             select="//parameter[starts-with(@name, 'Level') and
                                 ends-with(@name, '_stratum')]" />
      <xsl:value-of select="concat(count($allStrata), ' strata. ')"/>

      <!-- Determines whether all strata have the same values by comparing them all 
             against the first one. -->
      <xsl:variable name="allStrataEqual" 
                    select="not($allStrata[not(@value = $allStrata[1]/@value)])" />

      <xsl:value-of select="concat('All equal: ', $allStrataEqual)" />
    </xsl:template>
</xsl:stylesheet>

如果在上面的示例输入上运行此操作,结果为:

3 strata. All equal: true

如果在将第三个value更改为8(或其他任何内容)后对您的示例输入运行此操作,则结果为:

3 strata. All equal: false
相关问题