I want to validate XPath expressions against a XML schema or a representation of a XML document. The intention is to not waste time going through all nodes and trying to find an element when the path expression itself is invalid.
Does XPath already do it? If not - how do I validate XPath expressions?
I want to validate XPath expressions against a XML schema or a representation of a XML document. The intention is to not waste time going through all nodes and trying to find an element when the path expression itself is invalid.
Does XPath already do it? If not - how do I validate XPath expressions?
Share Improve this question edited Mar 22 at 17:39 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 22 at 14:48 Kishan _ 1735Kishan _ 1735 11 3- This question is similar to: Determine if an XPath query is valid. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Filburt Commented Mar 22 at 15:28
- Even if an XPath is syntactically correct, it may not match the structure of a given XML document or conform to a schema (XSD). So the answer is NO. – Hermann12 Commented Mar 22 at 17:12
- @Filburt No, that question was asking whether the XPath is syntactically valid. This question is asking whether it is semantically valid relative to a particular XML schema. – Michael Kay Commented Mar 22 at 18:30
1 Answer
Reset to default 1From XPath 2.0, the language specification supports the notion of "schema awareness". It's an optional feature and not all XPath processors support it. One that does so is my company's product Saxon-EE - the feature is only available in the paid-for version.
It's easiest to use the feature via the XQuery API (XQuery is a superset of XPath)
For example, if I run this query:
import schema '' at 'data/books.xsd';
declare context item as document-node(schema-element(BOOKLIST)) external;
/BOOKLIST/BOOK[TITLE='Jane Eyre']
you might get the warning message:
Warning on line 1 column 127 of file:/Users/xxxxx/src/samples/:
SXWN9037 The complex type of element BOOKLIST does not allow a child element named BOOK
Notes:
The
import schema
declaration identifies the schema that the source document is expected to conform toThe
declare context item
declaration says specifically what element in the schema is expected to be the root of the source documentThe XPath expression is perfectly valid, but will select nothing (that is, an empty result sequence). The warning message is saying that the XPath compiler has detected statically that the expression cannot possibly select anything.
Using schema-awareness is a bit of an overhead but if you have very complex path expressions against a complex document structure it can save you a lot of time debugging.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744311097a4567949.html
评论列表(0条)