如何在C#/ .NET中验证给定的xpath字符串是否有效?
我不确定只是运行XPath并且捕获异常是一个有效的解决方案(把胆汁放在我的喉咙里一会儿) - 如果明天我遇到其他输入我还没有测试过怎么办?
如何在C#/ .NET中验证给定的XPath字符串是否有效?
您尝试从中构建XPathExpression
并捕获异常.
try { XPathExpression.Compile(xPathString); } catch (XPathException ex) { MessageBox.Show("XPath syntax error: " + ex.Message); }
答案非常接近Tomalak写的内容(修复了编译错误并将强制主体置于XML中):
public static class XPathValidator { ////// Throws an XPathException if public static void Validate(string xpath) { using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("is not a valid XPath /// "))) { XPathDocument doc = new XPathDocument(stream); XPathNavigator nav = doc.CreateNavigator(); nav.Compile(xpath); } } }
对于比@ Tomalak的答案更短的版本,您可以使用XPathExpression.Compile方法:
string xpath = "/some/xpath"; try { XPathExpression expr = XPathExpression.Compile(xpath); } catch (XPathException) { }