Reputation: 230008
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
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
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
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
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