tree1.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 tree1.res ; rm tree1.tmp
  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. #ifdef LIBXML_TREE_ENABLED
  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. * print_element_names:
  22. * @a_node: the initial xml node to consider.
  23. *
  24. * Prints the names of the all the xml elements
  25. * that are siblings or children of a given xml node.
  26. */
  27. static void
  28. print_element_names(xmlNode * a_node)
  29. {
  30. xmlNode *cur_node = NULL;
  31. for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
  32. if (cur_node->type == XML_ELEMENT_NODE) {
  33. printf("node type: Element, name: %s\n", cur_node->name);
  34. }
  35. print_element_names(cur_node->children);
  36. }
  37. }
  38. /**
  39. * Simple example to parse a file called "file.xml",
  40. * walk down the DOM, and print the name of the
  41. * xml elements nodes.
  42. */
  43. int
  44. main(int argc, char **argv)
  45. {
  46. xmlDoc *doc = NULL;
  47. xmlNode *root_element = NULL;
  48. if (argc != 2)
  49. return(1);
  50. /*
  51. * this initialize the library and check potential ABI mismatches
  52. * between the version it was compiled for and the actual shared
  53. * library used.
  54. */
  55. LIBXML_TEST_VERSION
  56. /*parse the file and get the DOM */
  57. doc = xmlReadFile(argv[1], NULL, 0);
  58. if (doc == NULL) {
  59. printf("error: could not parse file %s\n", argv[1]);
  60. }
  61. /*Get the root element node */
  62. root_element = xmlDocGetRootElement(doc);
  63. print_element_names(root_element);
  64. /*free the document */
  65. xmlFreeDoc(doc);
  66. /*
  67. *Free the global variables that may
  68. *have been allocated by the parser.
  69. */
  70. xmlCleanupParser();
  71. return 0;
  72. }
  73. #else
  74. int main(void) {
  75. fprintf(stderr, "Tree support not compiled in\n");
  76. exit(1);
  77. }
  78. #endif