I found this question in this SSC forum thread requesting help to shape the XML document. Here is the input XML document.
<Root> <Student>Jhon </Student> <Student> Luka </Student> <Post>1</Post> <Post>2</Post> </Root>
The expected output is as follows.
<Root> <Students> <Student>Jhon </Student> <Student> Luka </Student> </Students> <Posts> <Post>1</Post> <Post>2</Post> </Posts> </Root>
This type of formatting can be achieved through a simple FLWOR operation.
DECLARE @x XML = ' <Root> <Student>Jhon </Student> <Student> Luka </Student> <Post>1</Post> <Post>2</Post> </Root>' SELECT @x.query (' for $i in (Root) let $s := $i/Student let $p := $i/Post return <Root> <Students> {$s} </Students> <Posts>{$p}</Posts> </Root> ') /* Produces: <Root> <Students> <Student>Jhon </Student> <Student> Luka </Student> </Students> <Posts> <Post>1</Post> <Post>2</Post> </Posts> </Root> */
View All Labs: XQuery Labs - A Collection of XQuery Sample Scripts and Tutorials
Tags: XQuery, XQuery Tutorials, XQuery Lab, XQuery Functions, XQuery in TSQL, XQuery Training, XQuery Tutorial,
Nice. I always learn something new from your XML related articles/post.
Thanks for sharing.
Glad to hear that you found it helpful.