2012-04-25 61 views
2

有沒有一種簡單的方法,我怎麼能從libxml2中的xmlNode獲得C char *?我想得到這樣的東西:"<root id="01"><head>some</head><data>information</data></root>"char *getStringFromXmlNode(xmlNode *node)應該是什麼?libxml2所有xml到字符

回答

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; 
} 

至少我認爲這就是你要求的。希望能幫助到你。