在迭代xsl:for-each

时间:2015-06-10 14:54:41

标签: xml xslt

在XSLT中,我想迭代每个国家的一个节点。我不知道XML中有多少个国家......

使用该文件:

<catalog>
    <cd>
        <title>Empire Burlesque</title>            
        <country>USA</country>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <country>UK</country>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <country>USA</country>
    </cd>
    <cd>
        <title>Greatest Hits</title>
        <country>UK</country>
    </cd>

    <cd>
        <title>Greatest Hits</title>
        <country>FIN</country>
    </cd>
    <cd>
        <title>SUPER Greatest Hits</title>
        <country>SPA</country>
    </cd>
    <cd>
        <title>Greatest Hits2</title>
        <country>FIN</country>
    </cd>
 </catalog>

我需要按美国,英国,FIN和SPA的第一个节点进行迭代。我只想遍历每个国家的第一个,忘记附加节点。

有类似的东西:

<xsl:for-each select="catalog/cd[country='USA']">
  <xsl:if test="position() = 1">

我必须知道XSLT中每个国家的名称是什么......所以它对我不起作用......

1 个答案:

答案 0 :(得分:1)

我遇到此问题的最佳解决方案是使用Keys和operator | of xpath。

首先通过您想要迭代的字段创建一个键:

<xsl:key name="countries" match="catalog/cd" use="country" />

然后我迭代所有CD,但有一个特殊条件:

<xsl:for-each select="catalog/cd[count(.| key('countries', country)[1])=1 ]">

运算符 | 是xpath中的UNION运算符 一个节点的UNION自己导致单个节点,而不是2.这对解决方案非常重要。

。| key('countries',country)[1] 表示如果您正在为UNION迭代当前节点,则所有文档中该国家/地区的第一次出现都是同一个节点,那么我们想要迭代它。否则我们不要!

相关问题