1

我想使用 libxml2 在完整的 xml 中计算具有相同名称的标签。请建议libxml2中是否有任何直接返回计数的内置函数。

4

1 回答 1

0

使用 XPath 很容易。请参阅XPath 示例。获得xmlXPathEvalExpression的结果后,您只需编写:

xpathObj->nodesetval->nodeNr

这是给出的XPath 语法。例如//elem,要计算所有elem元素。

以及基于 xpath1.c 示例的完整功能:

int count(xmlDocPtr doc, const char* path)
{
    int count;
    xmlXPathContextPtr xpathCtx; 
    xmlXPathObjectPtr xpathObj; 

      /* Create xpath evaluation context */
    xpathCtx = xmlXPathNewContext(doc);
    if(xpathCtx == NULL) {
        fprintf(stderr,"Error: unable to create new XPath context\n");
        return(-1);
    }

    /* Evaluate xpath expression */
    xpathObj = xmlXPathEvalExpression(path, xpathCtx);
    if(xpathObj == NULL) {
        fprintf(stderr,"Error: unable to evaluate xpath expression \"%s\"\n", path);
        xmlXPathFreeContext(xpathCtx); 
        return(-1);
    }

    count = xpathObj->nodesetval->nodeNr;
    printf("count of %s: %d\n", path, count);

    xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx); 

    return count;
}
于 2012-09-25T07:13:50.417 回答