views:

261

answers:

1

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?

+3  A: 

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;
}
p00ya
How can i show the user a message describing how to fix the problem when NULL is returned? When using xmlXPathEvalExpression an error message is printed that shows where syntax is incorrect.
keep in mind i cannot use xmlXPathEvalExpression because do not have an xmlXPathContext at this stage in the program
see my answer: use xmlXPathCompile, not xmlXPathEvalExpression. You don't need an xmlXPathContext at all.
p00ya