1

我正在更新我的一些旧代码,并决定将所有与 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);
}
4

2 回答 2

2
XPathNodeIterator it = nav.Select("/Document//Tests/Test[Type='Failure']/Groups/Group/Name");
var groups = (from XPathNavigator @group in it select @group.Value).ToList();
于 2012-07-16T08:17:59.193 回答
2

Group这是通过 LINQ获取名称的粗略且现成的示例:

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 并期望返回特定的值。

于 2012-07-16T08:34:16.030 回答