Friday, May 6, 2011

Why is XPathSelectElement is giving a NullReferenceException?

The following code gives a NullReferenceException since XPathSelectElement can't navigate through the XPath expression I've given:

String description = (String)node.XPathSelectElement("//car").Attribute("description");

I've debugged this and verified that the node is being read correctly, and that the elements in my XPath are capitalized the same way that they are in my XML file. I know for a fact that there is a "car" element with an attribute called "description". How come this isn't working? Does it have something to do with needing a LocalName version of the XPath?

From stackoverflow
  • If your XML document makes use of namespaces, that might be the issue. If //car is in another namespace than the default, XPathSelectElement will not be able to find the node. (You will have to prefix with the correct namespace)

  • Even once you fix what is probably a namespace problem, you must still check to make sure that you found a car before you go looking for attributes.

  • Vivek, can you post the xml?

0 comments:

Post a Comment