How to wrap each return result with an XML node using Xquery?

99 views Asked by At

Perhaps its possible to add an additional for loop around each return, and so wrap the result with a node?

Modifying a w3 schools sample query:

nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ basex bookstore.category.name.xq 
<xml>
  <category>cooking</category>
  <title>Everyday Italian</title>
  <category>children</category>
  <title>Harry Potter</title>
  <category>web</category>
  <title>Learning XML</title>
  <category>web</category>
  <title>XQuery Kick Start</title>
</xml>nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ 
nicholas@mordor:~/flwor$ cat bookstore.category.name.xq 

xquery version "3.1";


<xml>
{
for $x in db:open("bookstore")/bookstore/book
order by $x/title
return (<category>{data($x/@category)}</category>,<title>{data($x/title)}</title>)
}
</xml>
nicholas@mordor:~/flwor$ 

how can I wrap each result with a book element?

The xml sample data:

<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">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

from the w3schools site.

1

There are 1 answers

2
Jack Fleeting On BEST ANSWER

Something like this should do it:

<xml>
{
for $x in db:open("bookstore")/bookstore/book
let $category := data($x/@category)
return (
for $book in $x  
  let $title := data($book/title)
  return(
<book>
<category>{$category}</category><title>{$title}</title>)
</book>)
)
}
</xml>

Output:

<xml>
  <book>
    <category>cooking</category>
    <title>Everyday Italian</title>)
</book>
  <book>
    <category>children</category>
    <title>Harry Potter</title>)
</book>
  <book>
    <category>web</category>
    <title>XQuery Kick Start</title>)
</book>
  <book>
    <category>web</category>
    <title>Learning XML</title>)
</book>
</xml>