【问题标题】:What's the most efficient way to do recursive XPath queries using libxml2?使用 libxml2 进行递归 XPath 查询的最有效方法是什么?
【发布时间】:2009-11-05 19:50:14
【问题描述】:

我为 libxml2 编写了一个 C++ 包装函数,它使我可以轻松地对 XML 文档进行查询:

bool XPathQuery(
    const std::string& doc,
    const std::string& query,
    XPathResults& results); 

但我有一个问题:我需要能够对我的第一个查询的结果执行另一个 XPath 查询。

目前我通过将整个子文档存储在我的 XPathResult 对象中来做到这一点,然后我将 XPathResult.subdoc 传递给 XPathQuery 函数。这是非常低效的。

所以我想知道 ... libxml2 是否提供任何可以轻松存储 xpath 查询的上下文(可能是对节点的引用?)然后使用该引用作为 xpath 根执行另一个查询的东西?

【问题讨论】:

    标签: c++ xpath libxml2


    【解决方案1】:

    您应该重复使用 xmlXPathContext 并更改其 node 成员。

    #include <stdio.h>
    #include <libxml/xpath.h>
    #include <libxml/xmlerror.h>
    
    static xmlChar buffer[] = 
    "<?xml version=\"1.0\"?>\n<foo><bar><baz/></bar></foo>\n";
    
    int
    main()
    {
      const char *expr = "/foo";
    
      xmlDocPtr document = xmlReadDoc(buffer,NULL,NULL,XML_PARSE_COMPACT);
      xmlXPathContextPtr ctx = xmlXPathNewContext(document);
      //ctx->node = xmlDocGetRootElement(document);
    
      xmlXPathCompExprPtr p = xmlXPathCtxtCompile(ctx, (xmlChar *)expr);
      xmlXPathObjectPtr res = xmlXPathCompiledEval(p, ctx);
    
      if (XPATH_NODESET != res->type)
        return 1;
    
      fprintf(stderr, "Got object from first query:\n");
      xmlXPathDebugDumpObject(stdout, res, 0);
      xmlNodeSetPtr ns = res->nodesetval;
      if (!ns->nodeNr)
        return 1;
      ctx->node = ns->nodeTab[0];
      xmlXPathFreeObject(res);
    
      expr = "bar/baz";
      p = xmlXPathCtxtCompile(ctx, (xmlChar *)expr);
      res = xmlXPathCompiledEval(p, ctx);
    
      if (XPATH_NODESET != res->type)
        return 1;
      ns = res->nodesetval;
      if (!ns->nodeNr)
        return 1;
      fprintf(stderr, "Got object from second query:\n");
      xmlXPathDebugDumpObject(stdout, res, 0);
    
      xmlXPathFreeContext(ctx);
      return 0;
    }
    

    【讨论】:

    • 这个测试程序在尝试调试打印 xmlxpath 对象时为我崩溃: xmlXPathDebugDumpObject(stdout, res, 0);我会看看我是否无法弄清楚发生了什么......
    • 看起来这与我构建或链接 libxml2.dll 的方式有关。奇怪的。无论如何,解决它。
    • 这就是我要找的。谢谢。 =)
    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 2010-09-08
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多