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"
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"));
}
/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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With