I required the following output
<name>Thomas Mapother</name>
<name>Tom Cruise</name>
using the below XML using XQuery FLOWR Expressions.
INSERT INTO XMLO1 VALUES ('<Contact>
<Names>
<Name Type = "Legal">
<First>Thomas</First>
<Middle>T</Middle>
<Last>Mapother</Last>
</Name>
<Name Type = "Stage">
<First>Tom</First>
<Middle>C</Middle>
<Last>Cruise</Last>
</Name>
</Names>
</Contact>')
I tried the below query. But it returns a different output.
SELECT xDoc.query('let $names := Contact/Names/Name
return <name>{
for $x in $names
return ($x/First,$x/Last)}
</name>')
FROM XMLO1
Something like this:
Or shred and recombine (will be faster):
From this and from Return multiple XML nodes and Custom parent tag using FLWOR XQuery , I think you're a bit confused about how FLWOR expressions work.
In the other question, you only wanted one wrapper element (
oldPlanes
), but you made the mistake of creating the element inside thereturn
clause of a FLWOR expression, which is executed once for each node selected by thefor
clause. In this question, you have made the opposite mistake: you want onename
element for eachName
in the input, so you need to generate it within thereturn
clause.So instead of
you want
Again, it can be simplified to
Many people coming to XQuery from a SQL background make the mistake of thinking that every query has to be a FLWOR expression. In fact, the vast majority of queries don't need variables and don't need FLWOR.