Return all nodes in an XML between two nodes

This is from a post (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3272546&SiteID=1) asking for getting all nodes between 2 nodes in the xml. Michael Rys suggested using >> and << as the node order comparison. The following is the code: 

declare @x xml;

set

@x = N‘<Contents>

text

<page ID="1"/>

text1

<s> text2 </s>

<t ID = "2" >text3</t>

text4jhjgghfghfg

<page ID="2"/>

text3

</Contents>’

;

— Get all the nodes between page ID=1 and 2

select

@x.query(‘/Contents/node()[. >> (/Contents/page[@ID="1"])[1]

and . << (/Contents/page[@ID="2"])[1]]’)

set @x = N‘<Contents>

<p dir="rtl" Align="right" />

<book>aaaaaaaa</book>

<test>bbbbbbbbbbbbbbbb</test>

<book>cccccccccccccccccc</book>

<thesuarus IDs=" ,24,11" ThesuarusID="7 "/>

<book>dddddddddddddddddd</book>

</Contents>’

;

— Get all the nodes between the first and second instance of book

select @x.query(‘/Contents/node()[.>> (/Contents/book)[1] and . << (/Contents/book)[2]]’);

 

Advertisements
This entry was posted in XML, XQuery and XPath. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s