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
");  
            return NULL;  
        }  
      
        result = xmlXPathEvalExpression(xpath, context);  
        xmlXPathFreeContext(context);  
        if (result == NULL) {  
            printf("xmlXPathEvalExpression return NULL
");  
            return NULL;  
        }  
      
        if (xmlXPathNodeSetIsEmpty(result->nodesetval)) {  
            xmlXPathFreeObject(result);  
            printf("nodeset is empty
");  
            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
");  
        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
", ((char*)XML_GET_CONTENT(cur->xmlChildrenNode)));  
                else if (!xmlStrcmp(cur->name, (const xmlChar *)"url"))  
                    printf("%s
", ((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

更多xpath的写法可参考

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

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

原文地址:https://www.cnblogs.com/catgatp/p/6505427.html