libxml2:在 xpath 中忽略命名空间

libxml2: namespace ignored in xpath

我认为,xpath //@ns1:* 必须 return 名称空间中的所有属性,与前缀 ns1 关联。但是 libxml2 returns 节点集的属性比我预期的要多。

这是我的测试代码。我在 win32 上尝试了 libxml2 2.7.8 版,在 linux.

上尝试了 2.9.1 版
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <stdio.h>
#include <string.h>

const char* sample_doc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
  "<root xmlns:na=\"urn:test1\">"
    "<el>First</el><!-- comment -->"
    "<el at=\"some attr\" na:a=\"stuff\">Second</el>"
  "</root>";

void die(const char* err)
{
  fprintf(stderr, "ERROR: %s\n", err);
  exit(1);
}

int test()
{
  xmlXPathContextPtr xpathCtx;
  xmlXPathObjectPtr xpathObj;
  xmlDoc *doc = xmlReadMemory(sample_doc, strlen(sample_doc), "noname.xml", NULL, 0);
  xpathCtx = xmlXPathNewContext(doc);
  if(! xpathCtx)
    die("xmlXPathNewContext");
  if(xmlXPathRegisterNs(xpathCtx, BAD_CAST "ns1", BAD_CAST "urn:test1") != 0)
    die("xmlXPathRegisterNs1");
  xpathObj = xmlXPathEvalExpression(BAD_CAST "//@ns1:*", xpathCtx);
  if(! xpathObj)
    die("xmlXPathEvalExpression");
  printf("Found %d nodes:\n", xpathObj->nodesetval->nodeNr);
  for(int i = 0; i < xpathObj->nodesetval->nodeNr; ++i)
  {
    xmlNodePtr n = xpathObj->nodesetval->nodeTab[i];
    xmlChar* t = xmlNodeGetContent(n);
    printf(" type: %d, name: %s, content: %s\n", n->type, n->name, t);
    xmlFree(t);
  }
  xmlXPathFreeObject(xpathObj);
  xmlXPathFreeContext(xpathCtx);
  xmlFreeDoc(doc);
  return 0;
}

int main()
{
  int rc;
  xmlInitParser();
  LIBXML_TEST_VERSION
  rc = test();
  xmlCleanupParser();
  return rc;
}

函数 xmlXPathEvalExpression returns 节点集有 2 个节点,而我预计只有一个。

结果:

$ ./test 
Found 2 nodes:
 type: 2, name: at, content: some attr
 type: 2, name: a, content: stuff

是 libxml 中的错误还是我的 xpath 错误?

这是 libxml2 中的一个错误,已在 2.9.2 版 this commit 中修复。