我正在更新我的一些旧代码,并决定将所有与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);
}发布于 2012-07-16 16:34:16
下面是一个通过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并期望某些值作为回报。
发布于 2012-07-16 16:17:59
XPathNodeIterator it = nav.Select("/Document//Tests/Test[Type='Failure']/Groups/Group/Name");
var groups = (from XPathNavigator @group in it select @group.Value).ToList();https://stackoverflow.com/questions/11500367
复制相似问题