代码之家  ›  专栏  ›  技术社区  ›  brasskazoo

如何使用XPath在一组元素中查找属性的最小值?

  •  29
  • brasskazoo  · 技术社区  · 17 年前

    如果我有XML,比如:

    <foo>
      <bar id="1" score="192" />
      <bar id="2" score="227" />
      <bar id="3" score="105" />
      ...
    </foo>
    

    我可以使用XPath查找 score ?

    编辑 当前位置我正在使用的工具( Andariel ant任务)不支持XPath 2.0解决方案。

    6 回复  |  直到 17 年前
        1
  •  43
  •   Jens Erat    13 年前

    /foo/bar/@score[not(. < ../../bar/@score)][1]
    

    最低要求:

    /foo/bar/@score[not(. > ../../bar/@score)][1]
    

    我对谓词进行了编辑,使其适用于任何序列 bar ,即使您决定更改路径。请注意,属性的父级是它所属的元素。

    如果将这些查询嵌入XSLT或ant脚本等XML文件中,请记住编码 < > &lt; 尊重 &gt; .

        2
  •  19
  •   Jens Erat    13 年前

    结果表明该工具不支持XPath2.0。

    XPath 1.0没有这样的功能 min() max() 函数,因此要找到这些值,我们需要对XPath逻辑进行一些处理,并比较节点同级上的值:

    最大值:

    /foo/bar[not(preceding-sibling::bar/@score >= @score) 
        and not(following-sibling::bar/@score > @score)]/@score
    

    /foo/bar[not(preceding-sibling::bar/@score <= @score) 
        and not(following-sibling::bar/@score < @score)]/@score
    

    如果将这些查询嵌入XSLT或ant脚本等XML文件中,请记住编码 < > &lt; 尊重 &gt; .

        3
  •  6
  •   JP Alioto    17 年前

    这应该有用。。。

    max(foo/bar/@score)
    

    ... 和

    min(foo/bar/@score)
    

    ... 看看这个 function reference .

        4
  •  5
  •   Graham Lower    14 年前

    输出最小值,当然您可以选择从具有最小值的节点输出@id,而不是选择。

    <xsl:for-each select="/foo">
      <xsl:sort select="@score"/>
      <xsl:if test="position()=1">
        <xsl:value-of select="@score"/>
      </xsl:if>
    </xsl:for-each>
    

    最大值相同:

    <xsl:for-each select="/foo">
      <xsl:sort select="@score" order="descending"/>
      <xsl:if test="position()=1">
        <xsl:value-of select="@score"/>
      </xsl:if>
    </xsl:for-each>
    
        5
  •  3
  •   kuy    17 年前

    试试这个:

    //foo/bar[not(preceding-sibling::bar/@score <= @score) and not(following-sibling::bar/@score <= @score)]
    

    也许这可以在XPath1.0上使用。

        6
  •  3
  •   Paulb    12 年前

    我知道这是五年前的事了。只要为可能搜索并遇到此问题的人添加更多选项。

    类似的东西在XSLT2.0中也适用于我。

    min(//bar[@score !='']/@score)
    

    这个 !='' 是为了避免产生NaN值的null(可能有更好的方法)

    下面是一个有效的xpath/xquery:

    //bar/@score[@score=min(//*[@score !='']/number(@score))]
    
    推荐文章