Search code examples
cxmlxpathlibxml2

libxml2: namespace ignored in xpath


I think, xpath //@ns1:* must return all attributes in namespace, associated with prefix ns1. But libxml2 returns nodeset with more attributes then i expect.

Here is my test code. I tried libxml2 version 2.7.8 on win32 and version 2.9.1 on linux.

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

Function xmlXPathEvalExpression returns nodeset with 2 nodes, while i expect just one.

Results:

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

Is that a bug in libxml or my xpath is wrong?


Solution

  • This was a bug in libxml2 which has been fixed with this commit in version 2.9.2.