2012-07-16 13 views
1

我正在更新我的一些舊代碼,並決定將所有從XPath相關的XML更改爲Linq(所以請同時學習linq)。我遇到了這個代碼,有人可以告訴我如何將其轉換爲linq語句?從`XPathNodeIterator`轉換爲`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); 
} 
+1

'XDocument xDoc = XDocument.Parse(...);''var groups = xDoc.Descendants(「Name」)。Select(n => n.Value).ToList();' – 2012-07-16 08:26:39

回答

2

這裏是通過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並期待一定的價值回報。 ();}

2
XPathNodeIterator it = nav.Select("/Document//Tests/Test[Type='Failure']/Groups/Group/Name"); 
var groups = (from XPathNavigator @group in it select @group.Value).ToList(); 
+1

Thanks,but you從ReSharper獲得這個:D?!!?我希望它更人性化! – 2012-07-16 08:22:40