Grammin Grammin - 1 year ago 246
C++ Question

How can I convert a xmlNodePtr, with all the xml formated, into a string?

I have the following, which makes an

and then I would like to convert that node into a string, keeping all of the xml formatting and stuff:

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


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;

My problem is that the node seems to get made fine but I don't know how to then convert the node into a std::string. I've also tried using
but I couldn't get either of them working. An example of how to convert from a node to a string would be much appreciated, Thanks.

Answer Source

The key was adding:

  xmlChar *s;
  int size;

  xmlDocDumpMemory((xmlDocPtr)noteKey, &s, &size);

  xmlString = (char *)s;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download