Chr*_*ris 4 c# xpath linq-to-xml
在C#中使用XML文件,我正在尝试将XPath查询转换为LINQ,我不知道如何实现最后一节:
XPath的:
variable.XPathSelectElements("procedures/menu[@id='value']/procedure[@id]")
Run Code Online (Sandbox Code Playgroud)
LINQ:
from el in variable.Descendants("procedures").Descendants("menu")
where el.Element("id").Value == "value"
Run Code Online (Sandbox Code Playgroud)
我已经修改了你的建议@Jon但我似乎在这里做了一个我无法解决的简单错误.
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"));
}
Run Code Online (Sandbox Code Playgroud)
/procedure[@id]选择具有"id"属性的所有"procedure"元素.但是,我不相信你应该Descendants在这种情况下使用.我相信你的查询应该是:
variable.Elements("procedures")
.Elements("menu")
.Where(x => (string) x.Attribute("id") == "value")
.Elements("procedure")
.Where(x => x.Attribute("id") != null);
Run Code Online (Sandbox Code Playgroud)
编辑:有一种更简单的方法来获取命令ID到列表中:
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();
Run Code Online (Sandbox Code Playgroud)