gpt4 book ai didi

c - libxml2:在 xpath 中忽略命名空间

转载 作者:行者123 更新时间:2023-11-30 16:43:20 24 4
gpt4 key购买 nike

我认为,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 错误?

最佳答案

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

关于c - libxml2:在 xpath 中忽略命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com