-
Notifications
You must be signed in to change notification settings - Fork 95
gokogiri node iteration
suntong edited this page Feb 26, 2016
·
3 revisions
I want to learn to use gokogiri, but there aren't many sample code I can find, so I'm translating a C code from
Libxml2: Everything You Need in an XML Library
http://www.codeguru.com/cpp/data/data-misc/xml/article.php/c14893
Here is the C code:
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
static void print_element_names(xmlNode * a_node)
{
xmlNode *cur_node = NULL;
for (cur_node = a_node; cur_node; cur_node =
cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
printf("node type: Element, name: %s\n",
cur_node->name);
}
print_element_names(cur_node->children);
}
}
int main(int argc, char **argv)
{
xmlDoc *doc = NULL;
xmlNode *root_element = NULL;
if (argc != 2) return(1);
LIBXML_TEST_VERSION // Macro to check API for match with
// the DLL we are using
/*parse the file and get the DOM/
if (doc = xmlReadFile(argv[1], NULL, 0)) == NULL){
printf("error: could not parse file %s\n", argv[1]);
exit(-1);
}
/*Get the root element nod/
root_element = xmlDocGetRootElement(doc);
print_element_names(root_element);
xmlFreeDoc(doc); // free document
xmlCleanupParser(); // Free globals
return 0;
}
The final working go code can be found at