我认为,xpath //@ns1:*
必须返回名称空间中与前缀ns1
相关联的所有属性。但是libxml2返回的节点集具有更多属性,然后我期待。
这是我的测试代码。我在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 返回带有2个节点的节点集,而我只想要一个节点。
结果:
$ ./test
Found 2 nodes:
type: 2, name: at, content: some attr
type: 2, name: a, content: stuff
这是libxml或我的xpath中的错误吗?