views:

281

answers:

3

I have this xml-file:

<objects>
  <object> 
    <value>test</value>
  </object>
  <object> 
    <value>foo</value>
  </object>
  <object> 
    <value>bar</value>
  </object>      
</objects>

Now, I want to query this xml, and retrieve all the object-elements where the text in the value-element = "foo"

Is there a easy way of doing this?

I have tried something like this:

var objects = from e in xml.Elements("value")
              where e.Value.Equals("foo", StringComparison.OrdinalIgnoreCase)
              select e.parent;

That does not work..

A: 
 var objects = from e in xml.Descendants("object").Elements("value")
                          where e.Value.Equals("foo", StringComparison.OrdinalIgnoreCase)
                          select e.Parent;
BFree
+3  A: 

I think you're looking for

xml.Descendants("value")

xml.Elements() just returns child elements... if xml is your root XDocument, it wouldn't return anything.

womp
Yes, Descendants and a trimming of the value solved my problem. Thanks.
Vegar
+1  A: 

You should use xml.Descendants assuming you are querying from the document root. Also, I'd prefer using string.Equals over the Equals method called off the string returned by the Value property of the element (only as a matter of preference.) For example:

var objects = from e in xml.Descendants("value")
                where string.Equals(e.Value, 
                                    "foo", 
                                    StringComparison.OrdinalIgnoreCase)
                select e.Parent;
Peter Meyer
For some reason, I ended up using string.Equals( )...
Vegar