使用xslt查找唯一节点

时间:2010-02-04 12:38:27

标签: xslt xpath unique

我有一个xml文档,其中包含一些带有id的“Item”元素。我想列出唯一的Item ID。但是Item元素不在列表中 - 它们可以位于xml文档中的任何深度 - 例如:


<Node>
  <Node>
    <Item id="1"/>
    <Item id="2"/>
  </Node>
  <Node>
    <Item id="1"/>
    <Node>
      <Item id="3"/>
    </Node>
  </Node>
  <Item id="2"/>
</Node>

我想输出1,2,3(或类似的表示)。如果这可以用单个xpath完成,那就更好了!

我已经看到了兄弟元素列表的这个例子,但是没有看到一般的xml树结构。我也限制使用xslt 1.0方法。谢谢!

3 个答案:

答案 0 :(得分:5)

试试这个(使用Muenchian grouping):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="item-id" match="Item" use="@id" />
    <xsl:template match="/Node">
        <xsl:for-each select="//Item[count(. | key('item-id', @id)[1]) = 1]">
            <xsl:value-of select="@id" />,
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:5)

使用单个XPath表达式选择所有唯一项(不进行索引,注意性能问题):

//Item[not(@id = preceding::Item/@id)]

答案 2 :(得分:0)

不确定这是不是你的意思,但以防万一。

在html中

<xsl:apply-templates select="item"/>

模板。

 <xsl:template match="id">
        <p>
        <xsl:value-of select="@id"/> - 
        <xsl:value-of select="."/> 
        </p>
    </xsl:template>