Skip to content

Instantly share code, notes, and snippets.

@khajavi
Last active December 17, 2015 23:29
Show Gist options
  • Save khajavi/5689538 to your computer and use it in GitHub Desktop.
Save khajavi/5689538 to your computer and use it in GitHub Desktop.
Example of parsing xml by evaluating xpath expression and libxml2
CC = gcc
CLIBS = `pkg-config libxml-2.0 --cflags --libs`
xpath: xpath_example.c
$(CC) xpath_example.c -o xpath_example.bin $(CLIBS)
clean:
rm -f *.o *.bin
<?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 4, 2009</datewritten>
<keyword>علمی</keyword>
</storyinfo>
<body>
<headline>This is the headline</headline>
<para>This is the body text.</para>
</body>
</story>
#include <libxml/parser.h>
#include <libxml/xpath.h>
int
main( int argc, char* argv[] ) {
char* docname;
xmlDocPtr doc;
xmlChar* xpath = (xmlChar*) "//keyword";
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar* keyword;
xmlXPathContextPtr context;
docname = argv[1];
doc = xmlParseFile( docname );
context = xmlXPathNewContext( doc );
result = xmlXPathEvalExpression( xpath, context );
xmlXPathFreeContext( context );
if( result ) {
nodeset = result->nodesetval;
for( i = 0; i < nodeset->nodeNr; i++ ) {
keyword = xmlNodeListGetString( doc, nodeset->nodeTab[i]->xmlChildrenNode, 1 );
printf( "keyword: %s\n", keyword );
xmlFree( keyword );
}
xmlXPathFreeObject( result );
}
xmlFreeDoc( doc );
xmlCleanupParser();
return (1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment