我有以下内容,它生成xmlNodePtr
,然后我想将该节点转换为字符串,保留所有xml格式和内容:
std::string toString()
{
std::string xmlString;
xmlNodePtr noteKey = xmlNewNode(0, (xmlChar*)"noteKeyword");
std::vector<Note *>::iterator iter = notesList_.begin();
while(iter != notesList_.end())
{
xmlNodePtr noteNode = xmlNewNode(0, (xmlChar*)"Note");
xmlNodePtr userNode = xmlNewNode(0, (xmlChar*)"User");
xmlNodePtr dateNode = xmlNewNode(0, (xmlChar*)"Date");
xmlNodePtr commentNode = xmlNewNode(0, (xmlChar*)"Comment");
xmlNodeSetContent(userNode, (xmlChar*)(*iter)->getUser().c_str());
xmlNodeSetContent(dateNode, (xmlChar*)(*iter)->getDate().c_str());
xmlNodeSetContent(commentNode, (xmlChar*)(*iter)->getComment().c_str());
xmlAddChild(noteNode, userNode);
xmlAddChild(noteNode, dateNode);
xmlAddChild(noteNode, commentNode);
xmlAddChild(noteKey, noteNode);
iter++;
}
xmlDocPtr noteDoc = noteKey->doc;
//this doesn't appear to work, do i need to allocate some memory here?
//or do something else?
xmlOutputBufferPtr output;
xmlNodeDumpOutput(output, noteDoc, noteKey, 0, 1, "UTF-8");
//somehow convert output to a string?
return xmlString;
}
我的问题是节点似乎变得很好但我不知道如何将节点转换为std :: string。我也尝试过使用xmlNodeListGetString
和xmlDocDumpFormatMemory
,但我无法让其中任何一个工作。如何从节点转换为字符串的示例将非常感谢,谢谢。
答案 0 :(得分:1)
关键是添加:
xmlChar *s;
int size;
xmlDocDumpMemory((xmlDocPtr)noteKey, &s, &size);
xmlString = (char *)s;
xmlFree(s);
答案 1 :(得分:0)
试试这个例子:
xmlBufferPtr buf = xmlBufferCreate();
// Instead of Null, you can write notekey->doc
xmlNodeDump(buf, NULL, noteKey, 1,1);
printf("%s", (char*)buf->content);
Ricart y Rambo签名。