Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to LINQ Conversion

Working with an XML file in C#, I'm trying to convert an XPath query to LINQ and I don't know how to achieve the last section:

XPath:

variable.XPathSelectElements("procedures/menu[@id='value']/procedure[@id]")

LINQ:

from el in variable.Descendants("procedures").Descendants("menu")
where el.Element("id").Value == "value"

How do I achieve the /procedure[@id] section?

I've modified to your suggestion @Jon but I seem to be making a simple error here that I cannot resolve.

XDocument doc = XDocument.Load("procedures.xml");
var query = doc.Elements("procedures")
               .Elements("menu")
               .Where(x => (string) x.Attribute("id") == "value")
               .Elements("procedure").Where(x => x.Attribute("id") != null);

public List<string> commands = new List<string>();
foreach (XElement procedure in query) {
    commands.Add(procedure.Attribute("id"));
}
like image 729
Chris Avatar asked Feb 26 '23 04:02

Chris


1 Answers

/procedure[@id] selects all "procedure" elements which have an "id" attribute. However, I don't believe you should be using Descendants in this case. I believe your query should really be:

 variable.Elements("procedures")
         .Elements("menu")
         .Where(x => (string) x.Attribute("id") == "value")
         .Elements("procedure")
         .Where(x => x.Attribute("id") != null);

EDIT: There's a simpler way of getting the command IDs into a list:

XDocument doc = XDocument.Load("procedures.xml");
var commands = doc.Elements("procedures")
                  .Elements("menu")
                  .Where(x => (string) x.Attribute("id") == "value")
                  .Elements("procedure")
                  .Where(x => x.Attribute("id") != null)
                  .Select(x => x.Attribute("id").Value)
                  .ToList();
like image 163
Jon Skeet Avatar answered Mar 07 '23 14:03

Jon Skeet