Chris Koston
Chris Koston

Reputation: 975

Get followin sibling in SQL Server XPath

Since SQL Server does not support following-sibling axis - what is the best way to get it? Let's say I have XML like this and I would like to get the first 'b' node after a node matching the value 'dog':

<root>
    <a>cat</a>
    <b>Cats don't like milk</b>
    <a>dog</a>
    <b>Dogs like everything</b>
</root>

Upvotes: 1

Views: 1588

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You could try something like this.

declare @X xml = '
<root>
    <a>cat</a>
    <b>Cats don''t like milk</b>
    <a>dog</a>
    <c>not this</c>
    <b>Dogs like everything</b>
    <b>and not this</b>
</root>'

select @X.query('(/root/b[. >> (/root/a[. = "dog"])[1]])[1]')

Upvotes: 8

Related Questions