Source Code File 05-05_nodehunt

05-05_nodehunt.c

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

#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif

xmlNodePtr found;

int node_hunt(xmlNodePtr n, const xmlChar *e)
{
    xmlNodePtr node;
    int r;

    for( node=n; node; node=node->next)
    {
        if( node->type==XML_ELEMENT_NODE )
        {
            if( !xmlStrcmp( node->name, e) )
            {
                found = node;
                return(TRUE);
            }
        }
        if( node->children )
        {
            r = node_hunt( node->children, e );
            if( r )
                return(r);
        }
    }
    return(FALSE);
}

int main()
{
    const char filename[] = "sample.xml";
    xmlDocPtr doc;
    xmlNodePtr root;
    int r;

    doc = xmlParseFile(filename);
    if( doc==NULL )
    {
        fprintf(stderr,"Unable to open %s\n",filename);
        exit(1);
    }

    root = xmlDocGetRootElement(doc);
    r = node_hunt(root, (const xmlChar *)"lastName");
    if( r )
    {
        printf("<%s> found\n",found->name);
        printf("Parent is <%s>\n",found->parent->name);
    }

    xmlFreeDoc(doc);

    return(0);
}

Output Screenshot

<lastName> found
Parent is <character>

Notes

* Ensure that you check the book to read about the flaw in the node_hunt() function.