问题
I'm playing with the bookstore XML from w3schools:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
which I query of using XQuery 3.1:
xquery version "3.1";
declare option output:method 'xml';
for $doc in db:open("bookstore")
let $books := $doc/bookstore/book
return(
for $book in $books
let $authors := $book/author
let $title := data($book/title)
return
<b>{
(<t>{$title}</t>,$authors)
}</b>
)
The output, so far as it goes, is the desired result.
the nested for loop of the query is comprehensible, but perhaps not "Xquery"-ish?
That a book has, at least for this example, a single title and yet multiple authors, creates, perhaps a bit of a mismatch insofar as the loop here is being used or misused.
output:
<b>
<t>Everyday Italian</t>
<author>Giada De Laurentiis</author>
</b>
<b>
<t>Harry Potter</t>
<author>J K. Rowling</author>
</b>
<b>
<t>XQuery Kick Start</t>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
</b>
<b>
<t>Learning XML</t>
<author>Erik T. Ray</author>
</b>
This question is not meant to be a code-review per se, more looking for alternate or more standard approaches. A not entirely unrelated tangent for context:
https://martinfowler.com/bliki/OrmHate.html
回答1:
I'm not sure what your question is, to be honest, but your XQuery can be simplified quite a bit
for $book in db:open("bookstore")/bookstore/book
return <b>
<t>{string($book/title)}</t>
{$book/author}
</b>
which results in the same nodes being created
<b>
<t>Everyday Italian</t>
<author>Giada De Laurentiis</author>
</b>
<b>
<t>Harry Potter</t>
<author>J K. Rowling</author>
</b>
<b>
<t>XQuery Kick Start</t>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
</b>
<b>
<t>Learning XML</t>
<author>Erik T. Ray</author>
</b>
来源:https://stackoverflow.com/questions/65275437/nested-looping-within-xquery-results-in-a-mismatch-and-idioms