| 1 |
/** |
| 2 |
* section: Tree |
| 3 |
* synopsis: Navigates a tree to print element names |
| 4 |
* purpose: Parse a file to a tree, use xmlDocGetRootElement() to |
| 5 |
* get the root element, then walk the document and print |
| 6 |
* all the element name in document order. |
| 7 |
* usage: tree1 filename_or_URL |
| 8 |
* test: tree1 test2.xml > tree1.tmp && diff tree1.tmp $(srcdir)/tree1.res |
| 9 |
* author: Dodji Seketeli |
| 10 |
* copy: see Copyright for the status of this software. |
| 11 |
*/ |
| 12 |
#include <stdio.h> |
| 13 |
#include <libxml/parser.h> |
| 14 |
#include <libxml/tree.h> |
| 15 |
|
| 16 |
/* |
| 17 |
*To compile this file using gcc you can type |
| 18 |
*gcc `xml2-config --cflags --libs` -o xmlexample libxml2-example.c |
| 19 |
*/ |
| 20 |
|
| 21 |
/** |
| 22 |
* print_element_names: |
| 23 |
* @a_node: the initial xml node to consider. |
| 24 |
* |
| 25 |
* Prints the names of the all the xml elements |
| 26 |
* that are siblings or children of a given xml node. |
| 27 |
*/ |
| 28 |
static void |
| 29 |
print_element_names(xmlNode * a_node) |
| 30 |
{ |
| 31 |
xmlNode *cur_node = NULL; |
| 32 |
|
| 33 |
for (cur_node = a_node; cur_node; cur_node = cur_node->next) { |
| 34 |
if (cur_node->type == XML_ELEMENT_NODE) { |
| 35 |
printf("node type: Element, name: %s\n", cur_node->name); |
| 36 |
} |
| 37 |
|
| 38 |
print_element_names(cur_node->children); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
/** |
| 44 |
* Simple example to parse a file called "file.xml", |
| 45 |
* walk down the DOM, and print the name of the |
| 46 |
* xml elements nodes. |
| 47 |
*/ |
| 48 |
int |
| 49 |
main(int argc, char **argv) |
| 50 |
{ |
| 51 |
xmlDoc *doc = NULL; |
| 52 |
xmlNode *root_element = NULL; |
| 53 |
|
| 54 |
if (argc != 2) |
| 55 |
return(1); |
| 56 |
|
| 57 |
/* |
| 58 |
* this initialize the library and check potential ABI mismatches |
| 59 |
* between the version it was compiled for and the actual shared |
| 60 |
* library used. |
| 61 |
*/ |
| 62 |
LIBXML_TEST_VERSION |
| 63 |
|
| 64 |
/*parse the file and get the DOM */ |
| 65 |
doc = xmlReadFile(argv[1], NULL, 0); |
| 66 |
|
| 67 |
if (doc == NULL) { |
| 68 |
printf("error: could not parse file %s\n", argv[1]); |
| 69 |
} |
| 70 |
|
| 71 |
/*Get the root element node */ |
| 72 |
root_element = xmlDocGetRootElement(doc); |
| 73 |
|
| 74 |
print_element_names(root_element); |
| 75 |
|
| 76 |
/*free the document */ |
| 77 |
xmlFreeDoc(doc); |
| 78 |
|
| 79 |
return 0; |
| 80 |
} |