在 xml 中找到每个元素的属性最大值?

find the max of an attribute per element in xml?

在过去的一个小时里,我一直在寻找如何找到按元素分组的事物的最大值,但没有成功。

我正在尝试报告每个用户播放次数最多的播放列表的 pid 和 uid 以及播放次数

这是我的 xml 文件:

<!DOCTYPE users SYSTEM "users.dtd">
<users>
 <user uid = "u1" dob = "06/03/94" email = "tom@hotmail.com">
    <surname> Doe</surname>
    <givennames> Jon </givennames>
    <follows who = "u1 u2"/>
    <playlists>
      <playlist pid = "p1" created ="12/03/11" playcount = "5" /> 
    </playlists>
   </user>

  <user uid = "u2" dob = "06/03/95" email = "jane@hotmail.com">
    <surname> Dod</surname>
    <givennames> Jane </givennames>
    <follows who = "u1 u3"/>
   </user>

   <user uid = "u3" dob = "06/04/95" email = "dave@hotmail.com">
    <surname> ron</surname>
    <givennames> dave </givennames>
    <follows who = "u1 u2"/>
    <playlists>
      <playlist pid = "p3" created ="12/02/09" playcount = "9"/> 
      <playlist pid = "p9" created = "11/11/11" playcount = "11"/>
     </playlists>
   </user>

   <user uid = "u4" dob = "06/04/99" email = "jeff@hotmail.com">
    <surname> dun</surname>
    <givennames> jeff</givennames>
     <follows who = "u1 u2 u3"/>
    <playlists>
      <playlist pid = "p4" created ="12/02/09" playcount = "3"/> 
      <playlist pid = "p6" created ="12/02/09" playcount = "55"/>
    </playlists>
   </user>

</users>

我试过

for $user in doc("users.xml")/users/user
 where $users/playlists/playlist/@playcount = max($users/playlists/playlist/@playcount)
   return $user

但它不起作用..我尝试过的任何东西都不起作用...它 returns 我每个用户的最大播放次数(这是我得到的最好的,因为这是个主意我想从这个查询中得到什么)或者我得到每个播放列表

我需要一个输出的查询:

<favorites>
   <user uid = "u1" pid = "p1" playcount = "5"/>
   <user uid = "u2" />
   <user uid = "u3" pid = "p9" playcount = "11"/>
   <user uid = "u4" pid = "p6" playcount = "55"/>
</favorites>

playlists 是一个可选元素,因此如果用户没有播放列表,则只需报告 uid..

有什么帮助吗?真的在这里我的智慧结束了,因为似乎很难找到一个查找使用按元素分组的 max 函数的查询的示例..

我猜你需要分支案例,还要自定义输出格式。这是我的 xquery:

let $users := doc("users.xml")/users/user
for $user in $users
let $maxCount := max($user/playlists/playlist/@playcount)
let $maxPlaylist := $user/playlists/playlist[@playcount = $maxCount]
return if (count($maxPlaylist) > 0)
then <user uid="{$user/@uid}" pid = "{$maxPlaylist/@pid}" playcount = "{$maxPlaylist/@playcount}"/>
else <user uid="{$user/@uid}"/>