Tuesday, 24 March 2015

xmlDoc.SelectSingleNode keeps same value in foreach loop


I have had an issue when looping through xml child nodes.

where using selector in loop kept same value.

xmlDoc.SelectSingleNode 

Example
var listOfNodes = xmlDoc.SelectSingleNode("//elementSelector");

foreach (XmlNode node in listOfNodes)
{
            var myValue = node.SelectSingleNode(@"//elementSelector").InnerText
}

myValue for each iteration returns same value even though the node changes


Solution is to add '.'

currentVenue.SelectSingleNode(@".//venueName").InnerText;


Now why this is:

The '.' in selector means to select the current node.
Without it, searching starts from the document root, not current element.