求子元素的总数?

发布于 2024-12-05 11:37:30 字数 434 浏览 0 评论 0原文

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <author>
        <name>A</name>
        <book>Book1</book>
        <book>Book2</book>
    </author>
    <author>
        <name>B</name>
        <age>45</age>
        <book>Book3</book>
    </author>       
</root>

如何编写 XQuery 来显示作者的书籍总数?

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <author>
        <name>A</name>
        <book>Book1</book>
        <book>Book2</book>
    </author>
    <author>
        <name>B</name>
        <age>45</age>
        <book>Book3</book>
    </author>       
</root>

How do I write a XQuery to display the total number of books by an author?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪你搞怪i 2024-12-12 11:37:30

一种方法是:

let $max-books = max(/root/author/count(book))
return /root/author[count(book) = $max-books]

它将返回所有撰写了最大数量书籍的作者。

作为一个衬垫,这可以简化为:

/root/author[count(book) = max(/root/author/count(book))]

另一种方法是:

(for $author in /root/author
 order by count($author/book) descending
 return $author/name)[1]

它将返回拥有最大书籍数量的作者。

One approach is:

let $max-books = max(/root/author/count(book))
return /root/author[count(book) = $max-books]

which will return all authors who have authored a maximum number of books.

As a one liner, this can be simplified to:

/root/author[count(book) = max(/root/author/count(book))]

Another way to do this is:

(for $author in /root/author
 order by count($author/book) descending
 return $author/name)[1]

which will return an author with the maximum number of books.

你是年少的欢喜 2024-12-12 11:37:30

@Fox:你不应该用“作业”来标记这个问题吗? ;-)

@Oliver Hallam:恕我直言,@Fox 希望列出每位作者以及该作者的书籍数量,而不是书籍数量最多的作者。

您的第一个查询

let $max-books = max(/root/author/count(book))
return /root/author[count(book) = $max-books]

包含语法错误。您应该使用“:=”而不是仅使用“=”。此外

@Fox:要找到解决方案,请查看 FLWOR 表达式。您可以使用“for”部分通过 XPath 表达式选择每个图书节点,并将每个节点绑定到 $book 变量。然后使用“let”部分定义两个变量($authorName 和 $amountOfBooks),并使用 $book 作为“起点”。最后,使用“返回”部分定义生成的 XML 所需的输出格式。

@Fox: should you not tag this question with "homework"? ;-)

@Oliver Hallam: IMHO, @Fox wants to list each author together with the amount of books by that author and not the author with the highest amount of books.

Your first query

let $max-books = max(/root/author/count(book))
return /root/author[count(book) = $max-books]

Contains a syntax error. You should use ":=" instead of only "=". Furthermore

@Fox: to find the solution, have a look at FLWOR expressions. You can use the "for" part to select each of the book nodes with an XPath expression and bind each node to a $book variable. Then use the "let" part to define two variables ($authorName and $amountOfBooks) using the $book as "starting point". Last, use the "return" part to define the output format you need for the resulting XML.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文