Featured Post

Trie implementation in C

Traversing and Printing the XML Tree

This program traverses the nodes of the XML Document and prints them in the order.
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

#ifdef LIBXML_TREE_ENABLED

static void
print_tree(xmlNode * root_node)
{
    xmlNode *cur_node = NULL;

    for (cur_node = root_node; cur_node; cur_node = cur_node->next)
    {
        if (cur_node->type == XML_ELEMENT_NODE)
        {
            printf("<%s>\n", cur_node->name);
        }

        print_tree(cur_node->children);
    }
}


int
main(int argc, char **argv)
{
    xmlDoc *doc = NULL;
    xmlNode *root_element = NULL;

    if (argc != 2)
        return(1);


    doc = xmlReadFile(argv[1], NULL, 0);

    if (doc == NULL )
    {
        printf("Document parsing failed!!! \n");
        exit (1);
    }
    
    root_element = xmlDocGetRootElement(doc);
    
    if (root_element == NULL)
    {
        printf("Document is empty\n");
        xmlFreeDoc(doc);
        exit(1);
    }

    print_tree(root_element);

    xmlFreeDoc(doc);

    xmlCleanupParser();

    return 0;
}
#else
int main(void)
{
    printf("Tree support not compiled in\n");
    exit(1);
}
#endif

Comments