Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating string with libxml2 (c++)

Tags:

c++

libxml2

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.

like image 565
leshka Avatar asked Nov 11 '10 15:11

leshka


2 Answers

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);
}
like image 120
Fred Foo Avatar answered Sep 22 '22 21:09

Fred Foo


Something I wrote while ago. Hope it helps....

xmlDocPtr pDoc = ... // your xml docuemnt

xmlCharPtr psOutput;
int iSize;
xmlDocDumpFormatMemoryEnc(pDoc, &psOutput, &iSize, "UTF-8", 1);

// psOutput should point to the string.

// Don't forget to free the memory.
xmlFree(psOutput);
like image 29
Kei Avatar answered Sep 19 '22 21:09

Kei