我在C中做一个程序,我希望从这个.xml doc获得两个IP。
我是这样做的,但它只返回第一个IP:
void parseGlobalStats(xmlDocPtr doc, xmlNodePtr cur) {
xmlChar *IP;
cur = cur->xmlChildrenNode;
cur = cur->next;
cur = cur->xmlChildrenNode;
while (cur != NULL)
{
if ((!xmlStrcmp(cur->name, (const xmlChar *)"IP")))
{
IP = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
printf("IP = %s\n",IP);
}
return;
}
}
编译得很好,但执行时只返回第一个IP(179.199.24.207)。如何创建一个从该doc获取2个IP并将其存储在字符串变量中的函数?
答案 0 :(得分:1)
由于您只是在查找某些全局统计信息(包括IP
),因此您可以使用 xpath评估。
使用 xpath ,以下文件[ test.xml ]:
<icestats>
<source mount="/stream">
<Listeners>2</Listeners>
<listener>
<IP>179.199.24.207</IP>
<UserAgent>cmus/v2.4.3</UserAgent>
<Connected>76810</Connected>
<ID>405</ID>
</listener>
<listener>
<IP>177.133.209.80</IP>
<UserAgent>WinampMPEG/5.0</UserAgent>
<Connected>72</Connected>
<ID>1435</ID>
</listener>
</source>
</icestats>
可以[[strong> test.c ]:
提取IP
/* refactored [minimal changes] from libxml2 tutorials
* [ http://www.xmlsoft.org/tutorial/apd.html ]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
xmlDocPtr getdoc (char *docname)
{
xmlDocPtr doc;
doc = xmlParseFile(docname);
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return NULL;
}
return doc;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath)
{
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc);
if (context == NULL) {
printf("Error in xmlXPathNewContext\n");
return NULL;
}
result = xmlXPathEvalExpression(xpath, context);
xmlXPathFreeContext(context);
if (result == NULL) {
printf("Error in xmlXPathEvalExpression\n");
return NULL;
}
if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
xmlXPathFreeObject(result);
printf("No result\n");
return NULL;
}
return result;
}
int main(int argc, char **argv)
{
char *docname = "test.xml";
xmlDocPtr doc;
xmlChar *xpath = (xmlChar*) "//IP";
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar *IP;
doc = getdoc(docname);
result = getnodeset (doc, xpath);
if (result)
{
nodeset = result->nodesetval;
for (i=0; i < nodeset->nodeNr; i++)
{
IP = xmlNodeListGetString(
doc,
nodeset->nodeTab[i]->xmlChildrenNode,
1);
printf("IP: %s\n", IP);
xmlFree(IP);
}
xmlXPathFreeObject (result);
}
xmlFreeDoc(doc);
xmlCleanupParser();
return (1);
}
示例输出:
./test
IP: 179.199.24.207
IP: 177.133.209.80
进一步参考