Search code examples
.netxmlxpathxpathnavigator

Can I use an XPathExpression compiled from one navigator with a different navigator?


If I get an XPathNavigator, and use it to compile an XPathExpression exp, what constraints are there on the way I can use exp? Can I use exp with a different navigator? I know that it runs, and seems to give correct results even if the compiling XPathNavigator was formed from a doc or node that is very different from the Evaluating XPathNavigator. But I don't know if it is safe.

Here's a rudimentary example of what I mean. It's nonsensical but illustrates the point

private object TestXPath(XmlNode n1, XmlNode n2)
{
  XPathNavigator nav1 = n1.CreateNavigator();
  XPathExpression exp = nav1.Compile("somexpath");

  // evaluate using the navigator that compiled exp
  object result = n1.Evaluate(exp);
  if (result == null)
  {
    XPathNavigator nav2 = n2.CreateNavigator();
    // evaluate using a navigator that did NOT compile exp.  Is this legal?
    result = nav2.Evaluate(exp);
  }
  return result;
}

Solution

  • You may freely use that expression on other navigators. According to Daniel Cazzulino, the document from which you create the original navigator is irrelevant, as the xpath expression compilation is independent of a document instance.
    http://weblogs.asp.net/cazzu/archive/2003/10/07/30888.aspx