我正在更新我的一些旧代码,并决定将与 XML 相关的所有内容从 XPath 更改为 Linq(因此同时学习 linq)。我遇到了这段代码,有人可以告诉我如何将其转换为 linq 语句吗?
var groups = new List<string>();
XPathNodeIterator it = nav.Select("/Document//Tests/Test[Type='Failure']/Groups/Group/Name");
foreach (XPathNavigator group in it)
{
groups.Add(group.Value);
}
最佳答案
这是一个通过 LINQ 获取 Group
名称的粗略示例:
static void Main(string[] args)
{
var f = XElement.Parse("<root><Document><Tests><Test Type=\"Failure\"><Groups><Group><Name>Name 123</Name></Group></Groups></Test></Tests></Document></root>");
var names =
f.Descendants("Test").Where(t => t.Attribute("Type").Value == "Failure").Descendants("Group").Select(
g => g.Element("Name").Value);
foreach (var name in names)
{
Console.WriteLine(name);
}
}
就我个人而言,这是我一直喜欢为其编写单元测试的代码类型,提供特定的 XML 并期望返回特定的值。
关于c# - 从 `XPathNodeIterator` 到 `linq` 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11500367/