XPath/XQuery:计数节点元素和 return 最小计数与父 id

XPath/XQuery: Count node elements and return min count with parent id

我会举个例子来更好地说明我自己。

示例:

<asdf>
    <parentnode id ="1">
           <childnode>
            ...
            </childnode>
            <childnode>
            ...
            </childnode>
    </parentnode>
    <parentnode id ="2">
            <childnode>
            ...
            </childnode>
            <childnode>
            ...
            </childnode>
            <childnode>
            ...
            </childnode>
    </parentnode>
    <parentnode id ="3">
            <childnode>
            ...
            </childnode>
    </parentnode>
</asdf>

我需要计算所有父节点的所有子节点,并返回给定父节点的子节点的最小数量及其 id。

对于这个例子,解决方案是:

<parentnode id="3" amount="1"/>

我真的不知道从哪里开始。我是否必须计算 for 循环中的不同元素,或者这是否也可以使用 Xpath 表达式? 我不确定这是否是正确的方向:

let $a := fn:doc('asdf.xml')/asdf/*
 return 
for $z in distinct-values($a/name() = childnode )
 order by count($z) ascending
 return $z)[1]
  • childnode
  • count() 对那些 parentnode 元素进行排序
  • 从那个排序的序列中,select 第一个,它是 childnode 个元素最少的那个
  • 然后使用 computed element constructor using the name() of the $least-children element, copying any of it's attributes, and then creating the @amount attribute using a computed attribute constructor 构造一个元素,并为其分配 childnode 元素的 count() 的值

.

let $least-children := 
  (for $parent in $a
   order by count($parent/childnode) ascending
   return $parent)[1]

return
  element {$least-children/name()} { 
    $least-children/@*, 
    attribute {"amount"} { count($least-children/childnode)} 
  }

另一种确定最小计数的方法是使用 min 函数:

let $parents := asdf/parentnode,
    $counts := $parents/count(childnode),
    $min := min($counts),
    $parent := $parents[index-of($counts, $min)]
return 
    <parentnode id="{$parent/@id}" amount="{$min}"/>