Sunday, May 1, 2011

LinqToXML: Getting elements with given value

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..

From stackoverflow
  •  var objects = from e in xml.Descendants("object").Elements("value")
                              where e.Value.Equals("foo", StringComparison.OrdinalIgnoreCase)
                              select e.Parent;
    
  • 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.

    Vegar : Yes, Descendants and a trimming of the value solved my problem. Thanks.
  • 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;
    
    Vegar : For some reason, I ended up using string.Equals( )...

0 comments:

Post a Comment