c# - 从 `XPathNodeIterator` 到 `linq` 的转换

标签 c# xml linq

我正在更新我的一些旧代码,并决定将与 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/

相关文章:

c# - C# 中正确的变量声明

c# - 复选框和页面重新加载

php - curl_exec 最长执行时间 - 是什么原因造成的?

c# - LINQ 中导航属性查询的 ArgumentException

C# 如何在文本文件中写入多行?

javascript - 从 Javascript 读取具有不同标记名的 XML

java - 线性布局发现意外的命名空间前缀 "xmlns"

c# - 扩展类型安全以防止脏数据被用于需要 "clean"数据的函数

c# - 字典的值 c# .net

c# - 对应用于 MongoDB 中数组元素中每个项目的函数进行排序