【问题标题】:XSLT 2.0: Get elements where attributes are distinctXSLT 2.0:获取属性不同的元素
【发布时间】:2013-11-04 14:44:24
【问题描述】:

我的 XML 格式如下:

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

我正在尝试声明一个 XSLT 2.0 变量,该变量将包含“id”唯一的所有元素。如果“id”不是唯一的,则只应输出第一个实例,以便变量存储:

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

以下代码将为我提供所有唯一的@id 属性,但不是它们的父项(项目):

<xsl:variable name="uniqueItems" select="distinct-values(/Items/Item/@id)"/>

我想做这样的事情:

<xsl:variable name="uniqueItems" select="distinct-values(/Items/Item/@id)/parent::node()"/>

但这显然是不正确的。

【问题讨论】:

    标签: xml xslt unique distinct-values


    【解决方案1】:

    给定

    <xsl:key name="id" match="Item" use="@id"/>
    

    你可以使用&lt;xsl:variable name="uniqueItems" select="/Items/Item[not(key('id', @id)[2])]"/&gt;

    或使用for-each-group 查找单个项目组:

    <xsl:variable name="uniqueItems" as="element(Item)">
      <xsl:for-each-group select="/Items/Item" group-by="@id">
       <xsl:if test="not(current-group()[2])">
        <xsl:sequence select="."/>
       </xsl:if>
      </xsl:for-each-group>
    </xsl:variable>
    

    如果你想消除重复,那么使用

    <xsl:variable name="uniqueItems" as="element(Item)">
      <xsl:for-each-group select="/Items/Item" group-by="@id">
       <xsl:sequence select="."/>
      </xsl:for-each-group>
    </xsl:variable>
    

    【讨论】:

    • 感谢您的回复。对于我最初的问题可能缺乏精确性,我深表歉意。我想要的是包含具有重复 ID 的任何内容的 first 出现。我实际上是在尝试忽略 @id 的重复值。
    • 非常感谢您的帮助。 for-each-group 结构非常适合我的需求。
    猜你喜欢
    • 1970-01-01
    • 2015-01-08
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多