Skip to content

Instantly share code, notes, and snippets.

@khajavi
Created June 1, 2013 09:49
Show Gist options
  • Save khajavi/5689856 to your computer and use it in GitHub Desktop.
Save khajavi/5689856 to your computer and use it in GitHub Desktop.
Example of parsing xml by libxml2
CC = gcc
CLIBS = `pkg-config libxml-2.0 --cflags --libs`
parse_xml: parse_xml.c
$(CC) -g -O0 parse_xml.c -o parse_xml.bin $(CLIBS)
clean:
rm -f *.o *.bin
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
int
main(int argc, char **argv) {
char *docname;
xmlDocPtr doc;
xmlNodePtr cur1;
xmlNodePtr cur2;
xmlChar* key;
docname = argv[1];
doc = xmlParseFile(docname);
cur1 = xmlDocGetRootElement(doc);
cur1 = cur1->xmlChildrenNode;
while (cur1 != NULL) {
if ((!xmlStrcmp(cur1->name, (const xmlChar *)"storyinfo"))){
cur2 = cur1;
cur2 = cur2->xmlChildrenNode;
while (cur2 != NULL) {
if ((!xmlStrcmp(cur2->name, (const xmlChar *)"keyword"))) {
key = xmlNodeListGetString(doc, cur2->xmlChildrenNode, 1);
printf("keyword: %s\n", key);
xmlFree(key);
}
cur2 = cur2->next;
}
}
cur1 = cur1->next;
}
xmlFreeDoc(doc);
return 0;
}
<?xml version="1.0"?>
<story>
<storyinfo>
<author>John Fleck</author>
<datewritten>June 2, 2002</datewritten>
<keyword>علمی</keyword>
</storyinfo>
<body>
<headline>This is the headline</headline>
<para>This is the body text.</para>
</body>
<storyinfo>
<author>Folan Bahman</author>
<datewritten>June 1, 2007</datewritten>
<keyword>تخیلی</keyword>
</storyinfo>
<body>
<headline>This is the headline</headline>
<para>This is the body text.</para>
</body>
</story>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment