Libxml2: Everything You Need in an XML Library

 

Figure 2: DOM tree example

Specifically, you’ll dissect the tree1.c example program and identify some common programming paradigms used. The purpose of this program is to parse a file to a tree, use xmlDocGetRootElement() to get the root element, and then walk the document and print all the element names in document order. This is about the easiest non-trivial sort of thing you can do in XML. For simplicity’s sake, you’ll assume that the XML file you want to parse is the first argument on the command line and output will go to stdout (console). Program listing follows:

 1 #include <stdio.h>
 2 #include <libxml/parser.h>
 3 #include <libxml/tree.h>
 4
 5 static void print_element_names(xmlNode * a_node)
 6 {
 7    xmlNode *cur_node = NULL;
 8
 9    for (cur_node = a_node; cur_node; cur_node =
         cur_node->next) {
10       if (cur_node->type == XML_ELEMENT_NODE) {
11          printf("node type: Element, name: %s\n",
               cur_node->name);
12       }
13       print_element_names(cur_node->children);
14    }
15 }
16
17 int main(int argc, char **argv)
18 {
19    xmlDoc *doc = NULL;
20    xmlNode *root_element = NULL;
21
22    if (argc != 2)  return(1);
23
24    LIBXML_TEST_VERSION    // Macro to check API for match with
                             // the DLL we are using
25
26    /*parse the file and get the DOM */
27    if (doc = xmlReadFile(argv[1], NULL, 0)) == NULL){
28       printf("error: could not parse file %s\n", argv[1]);
29       exit(-1);
30       }
31
32    /*Get the root element node */
33    root_element = xmlDocGetRootElement(doc);
34    print_element_names(root_element);
35    xmlFreeDoc(doc);       // free document
36    xmlCleanupParser();    // Free globals
37    return 0;
38 }

More by Author

Get the Free Newsletter!

Subscribe to Data Insider for top news, trends & analysis

Must Read