如何使用XPath在一组元素中查找属性的最小值? [英] How can I use XPath to find the minimum value of an attribute in a set of elements?

查看:377
本文介绍了如何使用XPath在一组元素中查找属性的最小值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有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解决方案.

解决方案

原来该工具不支持XPath 2.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;.

If I have XML like:

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

Can I use XPath to find the minimum and maximum values of score?

Edit: The tool i'm using (Andariel ant tasks) doesn't support the XPath 2.0 solution.

解决方案

Turns out the tool does not support XPath 2.0.

XPath 1.0 doesn't have the fancy min() and max() functions, so to find these values we need to be a little tricky with the XPath logic, and compare the values on the siblings of the node:

Maximum:

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

Minimum:

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

If embedding these queries in XML files like XSLT or ant scripts, remember to encode < and > as &lt; respecting &gt;.

这篇关于如何使用XPath在一组元素中查找属性的最小值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆