Lately I've been using XPathDocument and XNavigator to parse an XML file for a given XPath and attribute. It's been working very well, when I know in advance what the XPath is.
Sometimes though, the XPath will be one of several possible XPath values, and I'd like to be able to test whether or not a given XPath exists.
In case I'm getting the nomenclature wrong, here's what I'm calling an XPath - given this XML blob:
<bar baz="This is the value of the attribute named baz">
XPathDocument document = new XPathDocument(filename);
XPathNavigator navigator = document.CreateNavigator();
XPathNavigator node = navigator.SelectSingleNode("//foo/bar");
If you've given valid XPath but it doesn't match anything,
SelectSingleNode won't throw a
NullReferenceException - it will just return null.
If you pass
SelectSingleNode some syntactically invalid XPath, that's when it will throw an
So normally, you'd just need to test whether the returned value was null or not.