[xml] XML beginner's question



Hi all.
This is my first attempt at handling XML using libxml2.
My problem is very simple: I have a small XML file

<temper>
 <actual>
     <temp>9</temp>
     <timestamp>18.11.2008 11:41:18</timestamp>
 </actual>
</temper>

and I am trying to retrieve the "temp" value.
Reading on xmlsoft.org I found a good reference
(http://xmlsoft.org/tutorial/ar01s04.html) but when I try to implement it
all I get is a segfault.
Here's the code I got so far:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>

void parseTemp (xmlDocPtr doc, xmlNodePtr cur) {

        xmlChar *key;
        cur = cur->xmlChildrenNode;
        while (cur != NULL) {
            if ((!xmlStrcmp(cur->name, (const xmlChar *)"temp"))) {
                        key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1);
                        printf("Temperature: %s\n", key);
                        xmlFree(key);
            }
        cur = cur->next;
        }
    return;
}

int main(int argc, char **argv) {

        char *docname;

        if (argc <= 1) {
                printf("Usage: %s docname\n", argv[0]);
                return(0);
        }

        docname = argv[1];
        xmlDocPtr doc;
        xmlNodePtr cur;
        doc = xmlParseFile(docname);

        if (doc == NULL ) {
                fprintf(stderr,"Document not parsed successfully. \n");
                return;
        }

        cur = cur->xmlChildrenNode;
        while (cur != NULL) {
                if ((!xmlStrcmp(cur->name, (const xmlChar *)"actual"))){
                        parseTemp (doc, cur);
                }
        cur = cur->next;
        }

        return (1);
}


Code runs fine without printf(), so I am supposing xmlNodeListGetString()
might be failing. Any suggestions?

Andrew M.




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]