Libor Zapletal
Libor Zapletal

Reputation: 14102

libxml2 all xml to char

Is there an easy way how can I get in C char * from xmlNode in libxml2? I want to get something like this: "<root id="01"><head>some</head><data>information</data></root>" What should be in char *getStringFromXmlNode(xmlNode *node)?

Upvotes: 2

Views: 1422

Answers (1)

Anthony
Anthony

Reputation: 108

Something like this.

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

At least I think that is what you were asking. Hope it helps.

Upvotes: 2

Related Questions