Skip to content

Instantly share code, notes, and snippets.

@khajavi
Created June 1, 2013 11:08
Show Gist options
  • Save khajavi/5690030 to your computer and use it in GitHub Desktop.
Save khajavi/5690030 to your computer and use it in GitHub Desktop.
Example of adding new attribute to xml nodes by using libxml2 library.
/*
* adopted from http://xmlsoft.org/tutorial/apf.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;
char *uri;
xmlDocPtr doc;
xmlNodePtr cur;
xmlNodePtr newnode;
xmlAttrPtr newattr;
if (argc <= 2) {
printf("Usage: %s docname, uri\n", argv[0]);
return(0);
}
docname = argv[1];
uri = argv[2];
doc = xmlParseFile(docname);
cur = xmlDocGetRootElement(doc);
newnode = xmlNewTextChild (cur, NULL, "reference", NULL);
newattr = xmlNewProp (newnode, "uri", uri);
if (doc != NULL) {
xmlSaveFormatFile (docname, doc, 1);
xmlFreeDoc(doc);
}
return (1);
}
CC = gcc
CLIBS = `pkg-config libxml-2.0 --cflags --libs`
add_attr: add_attribute_example.c
$(CC) add_attribute_example.c -o add_attribute_example.bin $(CLIBS)
clean:
rm -f *.o *.bin
<?xml version="1.0"?>
<story>
<storyinfo>
<author>John Fleck</author>
<datewritten>June 2, 2002</datewritten>
<keyword>&#x62A;&#x62E;&#x6CC;&#x644;&#x6CC;</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