Verify an XPath in .NET

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?

Answers


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

You try to build an XPathExpression from it and catch the exception.

try 
{
    XPathExpression.Compile(xPathString);
}
catch (XPathException ex)
{
    MessageBox.Show("XPath syntax error: " + ex.Message);
}

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);
        }
    }
}

For a shorter version than @Tomalak's answer, you can just use the XPathExpression.Compile method:

string xpath = "/some/xpath";

try
{
    XPathExpression expr = XPathExpression.Compile(xpath);
}
catch (XPathException)
{

}

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...


Need Your Help

Is there a more Pythonic way to test if an object is a number or return its value?

python python-2.7

I have not tried decorators yet or functions within functions, but this current un-pythonic method seems a little convoluted. I dont like how I need to repeat myself when I check the return_type (3...