Jason Renaldo
Jason Renaldo

Reputation: 2822

LINQ to XML finding elements that occur if later element is present

Here is the XML I am dealing with:

enter image description here

And my code so far:

XDocument doc = XDocument.Load(@"C:\Users\morganjo\Desktop\bb-tasks.xml");

        var q = from val in doc.Descendants("property")
                select (string)val.Attribute("value");

        foreach (string str in q)
        {
            Console.WriteLine(str);
        }

That will get me the values of all the numbers in the element value. The problem I am having is this, I only need the value if the element 'name' is equal to 'period' or 'delay'. Since these occur after value, I am not sure how to get about this.

Upvotes: 0

Views: 56

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Attribute order doesn't matter. You can take it's value and filter elements using it:

var q = from val in doc.Descendants("property")
        where (string)val.Attribute("name") == "delay" || (string)val.Attribute("name") == "period"
        select (string)val.Attribute("value");

Or using let keyword to get attribute value and then use it twice:

var q = from val in doc.Descendants("property")
        let name = (string)val.Attribute("name")
        where name == "delay" || value == "period"
        select (string)val.Attribute("value");

Upvotes: 1

Related Questions