I would like to validate a user-provided XPath query to ensure that it is syntactically correct.
Does it make sense to "validate" an XPath query without an XML document?
How can i achieve such a thing in libxml?
I would like to validate a user-provided XPath query to ensure that it is syntactically correct.
Does it make sense to "validate" an XPath query without an XML document?
How can i achieve such a thing in libxml?
You can compile an XPath expression using libxml without evaluating it. See xmlXPathCompile. The return value should be NULL for invalid expressions.
#include <stdio.h>
#include <libxml/xpath.h>
#include <libxml/xmlerror.h>
void
handle_structured_error(void *userdata, xmlErrorPtr err)
{
printf("%s", err->message);
}
int
main(int argc, char **argv)
{
if (argc < 2)
return 1;
const char *expr = argv[1];
xmlXPathContextPtr ctx = xmlXPathNewContext(NULL);
xmlSetStructuredErrorFunc(ctx, &handle_structured_error);
xmlXPathCompExprPtr p = xmlXPathCtxtCompile(ctx, (xmlChar *)expr);
if (p) {
printf("Valid: %s\n", expr);
xmlXPathFreeCompExpr(p);
} else {
printf("Invalid: %s\n", expr);
}
xmlXPathFreeContext(ctx);
return 0;
}