ripper234
ripper234

Reputation: 230008

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?

Upvotes: 15

Views: 7531

Answers (4)

Tomalak
Tomalak

Reputation: 338148

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

Upvotes: 22

paul
paul

Reputation: 1705

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)
{

}

Upvotes: 6

ripper234
ripper234

Reputation: 230008

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

Upvotes: 5

Vincent Van Den Berghe
Vincent Van Den Berghe

Reputation: 5555

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

Upvotes: 1

Related Questions