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?
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With