Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify an XPath in .NET

Tags:

c#

.net

xpath

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?

like image 504
ripper234 Avatar asked Nov 21 '08 14:11

ripper234


3 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);
}
like image 79
Tomalak Avatar answered Oct 10 '22 01:10

Tomalak


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);
        }
    }
}
like image 28
ripper234 Avatar answered Oct 10 '22 03:10

ripper234


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

}
like image 44
paul Avatar answered Oct 10 '22 01:10

paul