Dump an XML document or XML node to string or file in C

It took me way too long to figure out how to dump an xml document or xml node to a string (memory) or a file export in C, so here are some premade functions ready for use.

void xml_node_to_file(char *path, xmlDoc *document, xmlNode *node) {
    FILE *f;
    f = fopen(path, "w");
    xmlElemDump (f, document, node);
    fclose(f);
}
/* free the result */
char *xml_node_to_string(xmlDoc *document, xmlNode *node)
{
    char *out;
    xmlBufferPtr buffer = xmlBufferCreate();
    int size = xmlNodeDump(buffer, document, node, 0, 1);
    out = malloc(size);
    strcpy(out, (char *)buffer->content);
    return out;
}

Usage example:

xmlDocPtr  document1;
xmlNodePtr root1;
char *dump1;

document1 = xmlParseDoc((xmlChar *)"<?xml version=\"1.0\"?><root><a></a><b></b></root>");
root1 = xmlDocGetRootElement(document1);
dump1 = xml_node_to_string(document1, root1);
printf("dump1: %s", dump1);

if(dump1) free(dump1);

xml_node_to_file("/tmp/dump1.txt", document1, root1);
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s