1

I have a XML structure like

<root>
 <row>
  <value>1</value>
</row>
<row>
 <value>2</value>
</row>
</root>

I want to get <row> where <value> = 2. Is it possible? Any example?

To be more precise the xml structure is like this

<root>
 <row>
   <value>1</value>
 </row>
 <root>
   <row>
    <value>2</value>
   </row>
 </root>
</root>
3
  • Your updated xml structure is not well formated...and you can also use @x.nodes('/roots/root/row') a(b) if i assume there is a roots of all root Commented Oct 8, 2014 at 11:19
  • Updated XML. No I don't have a root of all roots Commented Oct 8, 2014 at 11:22
  • This is wired xml structure. Your first node <row> is directly under the root and your second <row> is under the <root> of root. Commented Oct 8, 2014 at 11:31

1 Answer 1

4

Sure:

declare @x xml = '<root>
 <row>
  <value>1</value>
</row>
<row>
 <value>2</value>
</row>
</root>';

select @x.query('/root[1]/row[./value/text()="2"]');
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Roger. Could you also please explain it. Why root[1]?
@Garima, "1" in square brackets means "first instance of element". It makes no difference in your example, but you can get somewhat better performance with bigger XML.
Thanks @Roger. My mistake I made the wrong xml. Updated my question with the right one. Could you answer now. Sorry I am a newbie in this
@Garima, it isn't a well-formed XML (both aren't, actually). Each opened node has to be closed. In the first sample, the root node has no closing tag. The same is true in the second.
@Garima, that's worse, since you have your nodes of interest on different levels. You can employ "search everywhere" mode, but it can be very costly: select @x.query('//row[data(./value)="2"]');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.