如何将所有xml格式化后的xmlNodePtr转换为字符串

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

本文关键字:xmlNodePtr 转换 字符串 格式化 xml      更新时间:2023-10-16

我有以下内容,它生成了一个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::字符串。我也尝试过使用xmlNodeListGetStringxmlDocDumpFormatMemory,但它们都无法工作。一个如何从节点转换为字符串的例子将不胜感激,谢谢。

关键是添加:

  xmlChar *s;
  int size;
  xmlDocDumpMemory((xmlDocPtr)noteKey, &s, &size);
  xmlString = (char *)s;
  xmlFree(s);

试试这个例子:

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签名。