0

I have a XML file containing some elements like

 <root>
    <gp>
      <i>1</i>
      <i>3</i>
      <i>5</i>
    </gp>
    <gp>
      <i>5</i>
      <i>6</i>
    </gp>
     . 
     . 
 </root>

Now i want to write a query by which i will get all gp elements which contains the <i> element with value 5?`

1
  • Ienumerable<XElement> variable = document.Elements("gp").where( p => p. now here i got stuck because here we have to iterate <i> elements also Commented Apr 28, 2012 at 18:56

1 Answer 1

2
var results = from gp in doc.Descendants("gp")
              where gp.Elements("i").Any(i => (int)i == 5)
              select gp

And in method-based syntax:

var results = doc.Descendants("gp").Where(gp => gp.Elements("i").Any(i => (int)i == 5));
Sign up to request clarification or add additional context in comments.

3 Comments

I think it would be better to use i.value == "5", I don't think you can convert XElement to int.
@ErikPhilips: Yes you can, try it out
@ErikPhilips: Yes, you can. And not only to int: msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx

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.