The two following loops give different output, despite both doing essentially the same thing:
XPathNavigator nav = xmlDoc.CreateNavigator();
foreach (object v in (XPathNodeIterator)nav.Evaluate(@"//*[heads!=1]/name"))
{
Console.Out.WriteLine(v);
}
for (int i = 1; i <= 3; i++)
{
Console.Out.Write(i);
Console.Out.WriteLine(nav.Evaluate(string.Format("string(//*[heads!=1][{0}]/name)", i)));
}
Output:
Zaphod
Frankie and Benji
Eddie
1Zaphod
2Frankie and Benji
3
Why is “Eddie” missing off the end of the for loop?
The two XPath expression do not do “essentially the same thing”:
According to the XPath specification:
Analogously, the XPath expression
//*[heads!=1][3]/name(looking at the 3rd iteration that should yield Eddie right away) selects thenamechild of all descendant elements that are “the third children of their parents whose number of heads differs from 1”.i.e. the
3refers to the set of children that fulfil the indicated number of heads restriction within their parent node.Instead, try:
/descendant::*[heads!=1][{0}]/name