Skip to content

Instantly share code, notes, and snippets.

@khajavi
Created June 1, 2013 11:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khajavi/5690057 to your computer and use it in GitHub Desktop.
Save khajavi/5690057 to your computer and use it in GitHub Desktop.
Example of getting attribute value of xml node by using libxml2 library.
CC = gcc
CLIBS = `pkg-config libxml-2.0 --cflags --libs`
retrieve_attribute_value: retrieve_attribute_value_example.c
$(CC) retrieve_attribute_value_example.c -o retrieve_attribute_value_example.bin $(CLIBS)
clean:
rm -f *.o *.bin
/*
* adopted from http://xmlsoft.org/tutorial/apg.html
*/
#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 cur;
xmlChar *uri;
if (argc <= 1) {
printf("Usage: %s docname\n", argv[0]);
return(0);
}
docname = argv[1];
doc = xmlParseFile(docname);
cur = xmlDocGetRootElement(doc);
cur = cur->xmlChildrenNode;
while (cur != NULL) {
if ((!xmlStrcmp(cur->name, (const xmlChar *)"reference"))) {
uri = xmlGetProp(cur, "uri");
printf("uri: %s\n", uri);
xmlFree(uri);
}
cur = cur->next;
}
xmlFreeDoc(doc);
return (1);
}
<?xml version="1.0" encoding="utf-8"?>
<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>
<reference uri="www.w3.org/TR/xslt20/"/></story>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment