有没有一种简单的方法可以让我从 libxml2 中的 xmlNode 获取 C char *?我想得到这样的东西:"<root id="01"><head>some</head><data>information</data></root>"
应该是什么char *getStringFromXmlNode(xmlNode *node)
?
问问题
1252 次
1 回答
2
像这样的东西。
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/tree.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void* getValueFromXML(xmlDocPtr doc, xmlChar *xpath )
{
xmlXPathObjectPtr result;
xmlNodeSetPtr nodeset;
xmlChar *keyword;
char *copiedStringPtr;
// Nodes are
// parse the xml document and find those nodes that meet the criteria of the xpath.
result = getnodeset(doc, xpath);
// if it parsed and found anything
if (result)
{
// get the nodes that matched.
nodeset = result->nodesetval;
// go through each Node. There are nodeNr number of nodes.
// nodeset is the seta of all nodes that met the xpath criteria
// For the API look here http://xmlsoft.org/html/libxml-xpath.html
if (nodeset->nodeNr>1)
{
printf("Returned more than one value. Fix the xpath\n");
return NULL;
}
keyword = xmlNodeListGetString(doc, nodeset->nodeTab[0]->xmlChildrenNode, 1);
//printf("keyword: %s\n", keyword);
copiedStringPtr = strdup((const char *)keyword);
xmlFree(keyword);
xmlXPathFreeObject (result);
}
return copiedStringPtr;
}
xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath)
{
xmlXPathContextPtr context; //http://xmlsoft.org/html/libxml-xpath.html#xmlXPathContext
xmlXPathObjectPtr result; // http://xmlsoft.org/html/libxml-xpath.html#xmlXPathObject
// http://xmlsoft.org/html/libxml-xpath.html#xmlXPathNewContext
context = xmlXPathNewContext(doc);
if (context == NULL)
{
printf("Error in xmlXPathNewContext\n");
return NULL;
}
//http://xmlsoft.org/html/libxml-xpath.html#xmlXPathEvalExpression
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;
}
至少我认为这就是你要问的。希望能帮助到你。
于 2012-04-30T18:20:52.123 回答