Dumbo
Dumbo

Reputation: 14102

Conversion from `XPathNodeIterator` to `linq`

I am updating some old code of mine and decided to change everything XML related from XPath to Linq (So learn linq meanwhile). I came across this code, Can someone please tell me how to translate this to a linq statement?

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);
}

Upvotes: 1

Views: 2266

Answers (2)

Tomtom
Tomtom

Reputation: 9384

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

Upvotes: 2

Jason Evans
Jason Evans

Reputation: 29186

Here's a rough and ready example of getting the Group names via 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);    
            }
        }

Personally this is the kind of code I always like to write unit tests for, giving certain XML and expecting certain values in return.

Upvotes: 2

Related Questions