gpt4 book ai didi

c - libxml2 和 XPath 在 ANSI C 中遍历 child 和 sibling

转载 作者:行者123 更新时间:2023-12-03 15:49:31 26 4
gpt4 key购买 nike

我已经在 Perl 中完成了相当多的 XML 工作,现在我需要在 ANDI C 中为一个项目完成这些工作。这是我用 XML 片段编写的代码。我在一定程度上取得了成功,但在获得 sibling 方面遇到了问题,我相信这非常容易,但我就是做不到。有两个函数,一个简单地获取节点集(直接从 xmlsoft.org 复制)。第二个功能是我的。

xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){

xmlXPathContextPtr context;
xmlXPathObjectPtr result;

context = xmlXPathNewContext(doc);
if (context == NULL) {
printf("Error in xmlXPathNewContext\n");
return NULL;
}

result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);

if (result == NULL) {
printf("Error in xmlXPathEvalExpression\n");
return NULL;
}

if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
xmlXPathFreeObject(result);
printf("No result\n");
return NULL;
}

return result;
}

void reader(xmlDocPtr xmlDoc, char *xpath)
{

xmlXPathObjectPtr xpathresult;
xmlNodeSetPtr node;
xmlNodeSetPtr node2;
xmlChar *title;

int cnt;

// parse feed in memory to xml object
doc = xmlReadMemory(xmlDoc,strlen(xmlDoc),"noname.xml",NULL,0);

if (!doc) criterr("Error parsing xml document");

// get xpath node set (ttn retrieves the value from the token table)
xpathresult = getnodeset(doc, ( xmlChar * ) xpath);

if (xpathresult) {
node = xpathresult->nodesetval;
printf("Content-type: text/html\n\n");

for (cnt=0;cnt<node->nodeNr; cnt++) {

title = xmlNodeListGetString(doc, node->nodeTab[cnt]->xmlChildrenNode,1);

printf("%d) title= %s<br/>\n",cnt,title);
xmlFree(title);
}

xmlXPathFreeObject(xpathresult);
xmlFreeDoc(doc);
xmlCleanupParser();

} else {
criterr("Xpath failed");
}

xmlFreeDoc(doc);

criterr("Success");
}

和 xml 片段

<item>
<title>this is the title</title>
<link>this is the link</link>
<description>this is the description</description>
</item>

如果我使用像 //item/title 这样的 XPath,我会得到所有的标题,但我真正想要的是得到项目,然后在 node->nodeNr 循环中,能够轻松获取标题、链接和描述,因为我有 100 个“项目” block ,我只是不确定如何轻松获取该 block 的子项或 sibling 。

最佳答案

使用xmlNextElementSibling .如何找到它?转到 Tree API , 搜索sibling

这是你的循环,现在也获得了链接。

    for (cnt=0;cnt<node->nodeNr; cnt++) {
xmlNodePtr titleNode = node->nodeTab[cnt];
// titleNode->next gives empty text element, so better:
xmlNodePtr linkNode = xmlNextElementSibling(titleNode);

title = xmlNodeListGetString(doc, titleNode->xmlChildrenNode,1);
link = xmlNodeListGetString(doc, linkNode->xmlChildrenNode,1);

printf("%d) title= %s<br/>, link=%s\n",cnt,title,link);
xmlFree(title);
xmlFree(link);
}

titleNode->next 也可以指向链接,参见 how to get these XML elements with libxml2? .

生 child ? xmlFirstElementChild并循环 while node->next

关于c - libxml2 和 XPath 在 ANSI C 中遍历 child 和 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12538691/

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