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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值