XPath 到 LINQ 的转换
在 C# 中使用 XML 文件时,我尝试将 XPath 查询转换为 LINQ,但我不知道如何实现最后一部分:
XPath:
variable.XPathSelectElements("procedures/menu[@id='value']/procedure[@id]")
LINQ:
from el in variable.Descendants("procedures").Descendants("menu")
where el.Element("id").Value == "value"
如何实现 /procedure[@id] 部分?
我已经修改了你的建议@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"));
}
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"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
/procedure[@id]
选择所有具有“id”属性的“procedure”元素。但是,我认为在这种情况下您不应该使用后代
。我相信您的查询实际上应该是:编辑:有一种更简单的方法可以将命令 ID 放入列表中:
/procedure[@id]
selects all "procedure" elements which have an "id" attribute. However, I don't believe you should be usingDescendants
in this case. I believe your query should really be:EDIT: There's a simpler way of getting the command IDs into a list: