Get element with min attribute

走远了吗. 提交于 2019-12-25 03:25:00

问题


With Xquery I want to get the row which has the min sortOrder. In the example below the row with id=3.

<table>
  <row id="1"><attribute identifier="sortOrder">120</attribute><attribute identifier="mainContent">Test 3</attribute></row>
  <row id="2"><attribute identifier="sortOrder">130</attribute><attribute identifier="mainContent">Test 1</attribute></row>
  <row id="3"><attribute identifier="sortOrder">10</attribute><attribute identifier="mainContent">Test 2</attribute></row>
</table>

Anyone got a hint?


回答1:


find min value with the min() function and then look it up in the rows:

let $min := min(//row/attribute[@identifier='sortOrder'])
return //row[attribute[@identifier='sortOrder'] = $min]



回答2:


If you have access to an XQuery 3.0 implementation, then I am quite taken by this functional approach:

xquery version "3.0";

let $apply := function($xs, $f, $xpath) {
  $xpath($xs[. = $f($xs)])
} return


$apply(
    //row/attribute[@identifier eq 'sortOrder'],
    fn:min#1,
    function($x) {
        $x/parent::node()
    }
)

One of the nice properties of this approach is you only need to do the search on the initial data once i.e. //row/attribute[@identifier eq 'sortOrder'] only needs to be evaluated once, which may be more efficient.

Another nice property is that the lambda $apply is a generic function, and so you could re-use it for any function that would operate on $xs for example fn:max#1 :-)



来源:https://stackoverflow.com/questions/25641740/get-element-with-min-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!