tags:

views:

416

answers:

3

How can I verify a given xpath string is valid in C#/.NET?

I'm not sure just running the XPath and catching exceptions is a valid solution (putting aside the bile in my throat for a moment) - what if tomorrow I run into some other input I haven't tested against?

+3  A: 

You try it out and catch the exception.

An empty document will be enough.

XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
try 
{
  XPathExpression expr = nav.Compile(xPathString);
}
catch (XPathException)
{
  MessageBox.Show("Your XPath is invalid");
}
Tomalak
Try it on what, specifically? Can't I get to some other code path that will fail (when running this XPath on some other text)
ripper234
Darn. I just typed it into the answer instead of trying it with VS first. Of course "XPathDocument" was wrong.
Tomalak
A: 

Use a 'mild' regular expression to filter out complete garbage. If it passes the regex, just execute the query and catch exceptions, like mentioned above...

Vincent Van Den Berghe
+1  A: 

The answer is very close to what Tomalak wrote (fixed compilation error & put a mandatory body to the XML):

public static class XPathValidator
{
    /// <summary>
    /// Throws an XPathException if <paramref name="xpath"/> is not a valid XPath
    /// </summary>
    public static void Validate(string xpath)
    {
        using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("<xml></xml>")))
        {
            XPathDocument doc = new XPathDocument(stream);
            XPathNavigator nav = doc.CreateNavigator();
            nav.Compile(xpath);
        }
    }
}
ripper234
Please check my answer again, I did not intend to use "XPathDocument" at all.
Tomalak