c语言libxml2使用xpath解析示例
2021-07-30 本文已影响0人
一路向后
1.xml文件样本xpathtest.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>
2.源码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
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;
}
int main(int argc, char **argv)
{
xmlDocPtr doc;
xmlChar *xpath = BAD_CAST("/radios/radio[name='DEU-Antenne Bayern']");
xmlChar *value = NULL;
xmlXPathObjectPtr appResult = NULL;
xmlNodeSetPtr nodeset = NULL;
xmlNodePtr cur = NULL;
char *szDocName;
int i;
if(argc <= 1)
{
printf("Usage: %s docname\n", argv[0]);
return 0;
}
szDocName = argv[1];
/*解析文件*/
doc = xmlReadFile(szDocName, "UTF-8", XML_PARSE_RECOVER);
if(doc == NULL)
{
fprintf(stderr, "Document not parsed successful.\n");
return -1;
}
appResult = getNodeSet(doc, xpath);
if(appResult == NULL)
{
printf("App result is NULL\n");
xmlFreeDoc(doc);
return -1;
}
nodeset = appResult->nodesetval;
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(appResult);
return 0;
}
3.编译源码
$ gcc -o XPathXmlFile XPathXmlFile.c -I/usr/local/include/libxml2 -L/usr/local/lib -lxml2
4.运行及其结果
$ ./XPathXmlFile xpathtest.xml
DEU-Antenne Bayern
http://mp3.webradio.antenne.de:80
DEU-Antenne Bayern
http://test