【发布时间】:2010-11-11 15:00:00
【问题描述】:
我的问题是我想创建 xml 树并获得一个简单的字符串对象(甚至是 char*)。 而且我无法将 xml 保存到文件中。
所以在输入中我有带有完整 xml 树的 xmlDocPtr,并且想要获取包含 xml 但不使用文件的字符串。
感谢关注。
【问题讨论】:
我的问题是我想创建 xml 树并获得一个简单的字符串对象(甚至是 char*)。 而且我无法将 xml 保存到文件中。
所以在输入中我有带有完整 xml 树的 xmlDocPtr,并且想要获取包含 xml 但不使用文件的字符串。
感谢关注。
【问题讨论】:
使用xmlDocDumpMemory 或其任何表亲。用法:
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);
}
【讨论】:
我之前写的东西。希望对您有所帮助....
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);
【讨论】:
如果您使用 xmlDocDumpMemory() 请小心。在使用 xmlDocDumpMemory() 之后,在最后调用 xmlCleanupParser()。似乎 xmlDocDumpMemory() 在内部使用它。
【讨论】:
我无法得到你想要的,但在更改节点值后,你可以使用 xmlDocDump 将其保存easily。
【讨论】: