开发者

validate an xpath expression in Java

Given an user input string, how can I tell whether it is a valid Xpath expression or not开发者_Go百科 in Java. Just curious, since I cannot find a way to do it using javax.xml.xpath library. Thanks.


I assume you want to validate the syntax but not if the expression is valid within the context of a your xml or xml schema. You can use the compile(..) method and it will throw an exception if the xpath is incorrect w.r.t the syntax.

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//book[author='Abc']/title/text()");


Run the XPath against some example XML document (e.g. <a/>). In most cases it won't return anything, but what you care about is whether it will throw an exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜