使用 xslt 键查找唯一值

Val*_*ath 5 html xml xslt xpath

<ROOT>
<AA Aattr="xyz1">
    <BB bAttr1="firefox"  bAttr2="aaa" >
    </BB>   
    <BB bAttr1="chrome"   bAttr2="aaa" >
    </BB>
    <BB bAttr1="firefox"  bAttr2="bbb" >
    </BB>
    <BB bAttr1="chrome"   bAttr2="bbb" >
    </BB>
</AA>
<AA Aattr="xyz2">
    <BB bAttr1="firefox"  bAttr2="aaa" >
    </BB>   
    <BB bAttr1="chrome"   bAttr2="ccc" >
    </BB>
    <BB bAttr1="firefox"  bAttr2="ddd" >
    </BB>
</AA>
Run Code Online (Sandbox Code Playgroud)

我想在节点 'BB' 中选择属性 'bAttr2' 的不同\唯一值,从节点 'AA' 开始,其中属性 'Aattr' 是 xyz1

说对于给定的 xml,我需要输出为“aaa”、“bbb”

我使用密钥尝试了以下逻辑。但没有奏效。请帮忙

<xsl:key name="nameDistinct" match="BB" use="@bAttr1"/>
<xsl:template match="/">
<xsl:for-each select="ROOT/AA[@Aattr='xyz1']">
    <xsl:for-each select="BB[generate-id()=generate-id(key('nameDistinct',@bAttr2)[1])]">
    <xsl:value-of select="@bAttr2"/>            
    </xsl:for-each>
</xsl:for-each>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

JLR*_*she 5

您在这里有两个选择:

定义键时过滤键可用的项目:

  <xsl:key name="nameDistinct" match="AA[@Aattr = 'xyz1']/BB" use="@bAttr2"/>

  <xsl:template match="/">
    <xsl:for-each 
      select="ROOT/AA/BB[generate-id() =
                         generate-id(key('nameDistinct', @bAttr2)[1])]">
      <xsl:value-of select="@bAttr2"/>
    </xsl:for-each>
  </xsl:template>
Run Code Online (Sandbox Code Playgroud)

或在分组表达式中过滤:

  <xsl:key name="nameDistinct" match="BB" use="@bAttr2"/>

  <xsl:template match="/">
    <xsl:for-each 
      select="ROOT/AA/BB[generate-id() =
                         generate-id(key('nameDistinct', @bAttr2)
                                       [../@Aattr = 'xyz1']
                                       [1])]">
      <xsl:value-of select="@bAttr2"/>
    </xsl:for-each>
  </xsl:template>
Run Code Online (Sandbox Code Playgroud)

前一种方法不那么混乱,效率也稍高一些,而后者允许您对分组进行参数化(即对未硬编码为“xyz1”的值进行分组),例如:

  <xsl:key name="nameDistinct" match="BB" use="@bAttr2"/>

  <xsl:template match="/">
    <xsl:for-each select="ROOT/AA">
      <xsl:for-each
        select="BB[generate-id() =
                   generate-id(key('nameDistinct', @bAttr2)
                                    [../@Aattr = current()/@Aattr]
                                    [1])]">
        <xsl:value-of select="@bAttr2"/>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
Run Code Online (Sandbox Code Playgroud)