Creating string with libxml2 (c++)

leshka picture leshka · Nov 11, 2010 · Viewed 8.2k times · Source

My problem is that I want to create xml tree and get a simple string object (or even char*). And I can't save xml to file.

So in the input I have xmlDocPtr with complete xml tree and want to get string containing xml but without using files.

Thx for attention.

Answer

Fred Foo picture Fred Foo · Nov 11, 2010

Use xmlDocDumpMemory or any of its cousins. Usage:

void xml_to_string(xmlDocPtr doc, std::string &out)
{
    xmlChar *s;
    int size;
    xmlDocDumpMemory(doc, &s, &size);
    if (s == NULL)
        throw std::bad_alloc();
    try {
        out = (char *)s;
    } catch (...) {
        xmlFree(s);
        throw;
    }
    xmlFree(s);
}