简体   繁体   中英

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

Here is the XML I am dealing with:

在此处输入图片说明

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM