简体   繁体   中英

Creating string with libxml2 (c++)

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.

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);
}

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);

If you use xmlDocDumpMemory() be careful. Call xmlCleanupParser() at the very end, after using xmlDocDumpMemory(). It seems like xmlDocDumpMemory() uses it internaly.

我无法得到你想要的东西但是在更改节点值之后你可以使用xmlDocDump 轻松保存它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM