Validate XPath expression

浪子不回头ぞ 提交于 2020-01-15 09:41:37

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/1291826/validate-xpath-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!