gpt4 book ai didi

xml - 具有递归定义的 XPath

转载 作者:行者123 更新时间:2023-12-03 16:24:55 26 4
gpt4 key购买 nike

我有这样的 DTD:

     <!ELEMENT Root (Thread*) >
<!ELEMENT Thread(ThreadId, Message) >
<!ELEMENT Replies(message+) >
<!ELEMENT message(timestamp, sender, recipient, subject, text, Replies?)>

所以一个线程会有一条消息,这条消息可以有一个节点“回复”,然后这个节点可以包含消息等等,直到结构的底部。

现在我要做的是先检索消息最多的线程的 ID,然后检索嵌套回复链最长的线程的 ID。

这感觉像是一个递归问题,但我无法在 XPath 中处理它。到目前为止,我尝试过这样的事情:

      For $thread in //thread
Count(descendant-or-self::$thread/message)

对于每个线程,我尝试计算子消息节点的数量,但此解决方案计算线程的所有子节点的数量,因此包括回复节点。

我对这类问题感到迷茫,因为我不知道在这些“递归情况”下该怎么做。

最佳答案

假设您可以使用 XPath 3.0,例如

let $max := max(/Root/Thread/count(.//Message))
return /Root/Thread[count(.//Message) eq $max]/ThreadId

找到包含最多消息的线程的 ID,我认为

let $max := max(/Root/Thread/Message//Replies[not(Message/Replies)]/count(ancestor::Replies))
return /Root/Thread[Message//Replies[not(Message/Replies)]/count(ancestor::Replies) = $max]/ThreadId

查找具有最长嵌套回复链的线程的 ID。

在 XPath 2.0 中,您没有 let 表达式,因此您必须在引用变量的地方将示例中绑定(bind)的代码内联到变量中。

在 XPath 3.1 中,您有一个排序 函数 ( https://www.w3.org/TR/xpath-functions-31/#func-sort ),因此您可以排序并取最后一个,而不是计算最大值并选择具有最大值的项目

sort(/Root/Thread, (), function($t) { max($t/Message//Replies[not(Message/Replies)]/count(ancestor::Replies)) })[last()]/ThreadId

对于第二个更复杂的查询或

sort(/Root/Thread, (), function($t) { count($t//Message) })[last()]/ThreadId

第一个。

关于xml - 具有递归定义的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45173724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com