简体   繁体   English

在Java中验证xpath表达式

[英]validate an xpath expression in Java

Given an user input string, how can I tell whether it is a valid Xpath expression or not in Java. 给定用户输入字符串,如何判断它是否是Java中的有效Xpath表达式。 Just curious, since I cannot find a way to do it using javax.xml.xpath library. 只是好奇,因为我找不到使用javax.xml.xpath库的方法。 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. 我假设您要验证语法,但是如果表达式在xml或xml架构的上下文中有效则不会。 You can use the compile(..) method and it will throw an exception if the xpath is incorrect wrt the syntax. 您可以使用compile(..)方法,如果xpath与语法不正确,它将引发异常。

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 (eg <a/> ). 针对某些示例XML文档(例如<a/> )运行XPath。 In most cases it won't return anything, but what you care about is whether it will throw an exception. 在大多数情况下,它不会返回任何内容,但您关心的是它是否会抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM