libxml2用xpath进行查找


xml文档

<?xml version="1.0" encoding="UTF-8"?>
<radios>
    <radio>
        <name>Bayern</name>
        <url>http://mp3.webradio.antenne.de:80</url>
        <classification>
            <area>usa</area>
            <style>music</style>
        </classification>
    </radio>
    <radio>
        <name>DEU-Antenne Bayern</name>
        <url>http://mp3.webradio.antenne.de:80</url>
    </radio>
    <radio>
        <name>DEU-Antenne Bayern</name>
        <url>http://test</url>
    </radio>
</radios>

上代码

static xmlXPathObjectPtr getNodeset(xmlDocPtr doc, const xmlChar *xpath)
{
    xmlXPathContextPtr context;
    xmlXPathObjectPtr result;
    context = xmlXPathNewContext(doc);

    if (context == NULL) {
        printf("context is NULL\n");
        return NULL;
    }

    result = xmlXPathEvalExpression(xpath, context);
    xmlXPathFreeContext(context);
    if (result == NULL) {
        printf("xmlXPathEvalExpression return NULL\n");
        return NULL;
    }

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

    return result;
}


playlistDoc 为 xmlDocPtr类型.

    xmlChar *xpath = BAD_CAST("/radios/radio[name='DEU-Antenne Bayern']");   //关键在这行
    xmlXPathObjectPtr app_result = getNodeset(playlistDoc, xpath);
    if (app_result == NULL)
    {
        printf("app_result is NULL\n");
        return;
    }

    int i = 0;
    xmlChar *value;
    if(app_result)
    {
        xmlNodeSetPtr nodeset = app_result->nodesetval;
        xmlNodePtr cur;

        for (i=0; i < nodeset->nodeNr; i++)
        {
            cur = nodeset->nodeTab[i];   
            cur = cur->xmlChildrenNode;

            while (cur != NULL)
            {
                if (!xmlStrcmp(cur->name, (const xmlChar *)"name"))
                    printf("%s\n", ((char*)XML_GET_CONTENT(cur->xmlChildrenNode)));
                else if (!xmlStrcmp(cur->name, (const xmlChar *)"url"))
                    printf("%s\n", ((char*)XML_GET_CONTENT(cur->xmlChildrenNode)));

                cur = cur->next;
            }
        }

        xmlXPathFreeObject(app_result);
    }


输出:

DEU-Antenne Bayern
http://mp3.webradio.antenne.de:80
DEU-Antenne Bayern
http://test

xmlChar *xpath = BAD_CAST("/radios/radio[name='DEU-Antenne Bayern']"); 
改成

 xmlChar *xpath = BAD_CAST("/radios/radio[name='DEU-Antenne Bayern' and url='http://mp3.webradio.antenne.de:80']");
DEU-Antenne Bayern

输出:

http://mp3.webradio.antenne.de:80

更多xpath的写法可参考

http://www.w3.org/TR/xpath/

http://www.w3school.com.cn/xpath/index.asp

作者:帅得不敢出门   c++哈哈堂:31843264

你可能感兴趣的:(libxml2用xpath进行查找)