gpt4 book ai didi

xpath - 如何使用libxml依次应用两个xpath表达式?

转载 作者:行者123 更新时间:2023-12-03 16:23:03 24 4
gpt4 key购买 nike

综上所述,我是libxml的初学者,我必须使用现有的源代码。主要思想是应用第一个xpath表达式从xml文件中提取一组节点。然后,对于每个节点,应使用第二个xpath表达式提取一些值。

现有的源代码是:

int xt_parseXmlResult(xmlDocPtr doc, const char *xpath, assoc_arrayc_t expr, arrayc_t *result)
{
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);

// Register namespaces ...

/*
* Evaluate main xpath expression
*/
xmlXPathObjectPtr xpathNodes = xmlXPathEvalExpression((xmlChar *)xpath, xpathCtx);

/*
* Now we apply the xpath expressions on each node returned by the first xpath request
*/
// First loop is on the XML document as we have to create a new context each
// time we change the document
int nbDocs = xpathNodes->nodesetval->nodeNr;

for (row = 0; row < nbDocs; row++)
{
xmlXPathContextPtr subCtx = xmlXPathNewContext(doc);

// Register namespaces ...

// Update context to use the nodeset related to this row
subCtx->node = xpathNodes->nodesetval->nodeTab[row];

for (col = 0; col < expr.nbItems; col++)
{
// Evaluate expression
xpathRows = xmlXPathEvalExpression((xmlChar *)expr.itemList[col].val, subCtx);

result->data[(row + 1) * result->nbCols + col] = strdup((char *)xmlXPathCastToString(xpathRows));
xmlXPathFreeObject(xpathRows);
}
xmlXPathFreeContext(subCtx);
subCtx = NULL;
}

xmlFreeDoc(doc);
xmlXPathFreeContext(xpathCtx);
xmlXPathFreeObject(xpathNodes);
return 0;
}


我认为问题出在这条线

    // Update context to use the nodeset related to this row
subCtx->node = xpathNodes->nodesetval->nodeTab[row];


因为第二个xpath表达式是从xml文件的根目录而不是每个节点的根目录应用的。

关于如何做这种事情的任何想法?

最佳答案

一些示例代码。进行修改以适合您的需求和语言。这是C#,但应该大致相同。请注意,第二个xpath不是以“ /”开头,而是使用从第一个返回的节点的实例。两个xpath都不以“ /”结尾。

XmlDocument doc = new XmlDocument();
doc.Load(docfile);
XmlNodeList items = doc.SelectNodes("/part1/part2");
foreach (item in items)
{
XMLNode x = item.SelectNodes("part3");
//Dostuff
}

关于xpath - 如何使用libxml依次应用两个xpath表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/492577/

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