Last active
December 17, 2015 23:29
-
-
Save khajavi/5689538 to your computer and use it in GitHub Desktop.
Example of parsing xml by evaluating xpath expression and libxml2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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