【问题标题】:XPath/XQuery: Count node elements and return min count with parent idXPath/XQuery:计算节点元素并返回带有父 ID 的最小计数
【发布时间】:2020-08-31 15:45:37
【问题描述】:

我将举一个例子来更好地阐明自己。

例子:

<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]

【问题讨论】:

    标签: xml xpath xsd xquery


    【解决方案1】:
    • count()childnode 对这些parentnode 元素进行排序
    • 从该排序序列中,选择第一个,即childnode 元素数量最少的序列
    • 然后使用computed element constructor 使用$least-children 元素的name() 构造一个元素,复制它的任何属性,然后使用computed attribute constructor 创建@amount 属性,并为其分配@ 的值987654330@ 其中childnode 元素

    .

    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)} 
      }
    

    【讨论】:

    • 谢谢,但您能详细说明您的示例解决方案吗?
    • 另一个问题。是否可以更改具有未知文档结构的文档的 xquery ?我的意思是有一个更通用的解决方案,您不知道父节点和子节点的元素名称,而是从可能的最高节点开始?
    • 是的,这是可能的。如果您不确定元素的名称,但只知道 /*/* 是您想要计算的“父”元素,并且想要计算它的子元素?在答案中出现的每个位置将childnode 替换为*,它应该仍然有效。即order by count($parent/*) ascendingattribute {"amount"} { count($least-children/*)}
    【解决方案2】:

    确定最小计数的另一种方法是使用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}"/>
    

    【讨论】:

      猜你喜欢
      • 2012-01-10
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      相关资源
      最近更新 更多