Vegar
Vegar

Reputation: 12898

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

Upvotes: 1

Views: 822

Answers (3)

Peter Meyer
Peter Meyer

Reputation: 26051

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;

Upvotes: 1

womp
womp

Reputation: 116977

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.

Upvotes: 3

BFree
BFree

Reputation: 103740

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

Upvotes: 0

Related Questions