user3777206
user3777206

Reputation: 3

Check against multiple elements with one query?

Is it possible to check multiple elements inside of a root using where? I have a XML sheet setup in such a way that there are multiple elements with the same name (but only sometimes), like so:

<person>
    <name>Joe</name>
    <food>orange</food>
    <food>apple</food>
</person>
<person>
    <name>Roger</name>
    <food>apple</food>
</person>

I want to be able to check whether or not a person has a specific type of food and then output them into console. Using this method to grab them from the XML sheet:

var query = from c in xml.Root.Descendants("person")
                    where (string)c.Element("food") == "apple" 
                    select new c.Element("food").Value;

It will only add Roger to the query. I believe this is because apple is second, since when I switch it to being first on the list I get Joe to show up. Is there a way to check to see if the second element meets the where statement as well?

Upvotes: 0

Views: 49

Answers (3)

terrybozzio
terrybozzio

Reputation: 4532

You can try this out.It will return a projection with the name and food just to prove it has picked both:

var query = from c in xml.Root.Elements("person") //Descendants("person")
            from f in c.Descendants("food")
            where (string)f == "apple"
            select new { Food = f.Value,Name = c.Element("name").Value };

Output of query:

{Food = "apple", Name = "joe"}
{Food = "apple", Name = "Roger"}

Upvotes: 1

derpirscher
derpirscher

Reputation: 17400

Your code won't add "Roger", but "apple" to the resulting IEnumerable. I assume you want to select the name element of your person.

As an alternative to the previous answer, you could also search for all apples and then get the name element of their parents.

var result = xml.Root.Descendants("food")
    .Where(x=> (string)x == "apple")
    .Select(y=> (string)y.Parent.Element("name"));

should do the trick

Upvotes: 1

Erik Philips
Erik Philips

Reputation: 54638

Using Lambda (short cutting since apple is hard coded):

var doc = XDocument.Parse(@"<root><person><name>Joe</name><food>orange</food><food>apple</food></person><person><name>Roger</name><food>apple</food></person></root>");

var results = doc.Root.Descendants("person")
 .Where(p => p.Elements("food").Any(f => f.Value == "apple"))
 .Select(p => "apple");

DotNetFiddle Example

Upvotes: 0

Related Questions