【问题标题】:How can I convert a xmlNodePtr, with all the xml formated, into a string?如何将所有 xml 格式的 xmlNodePtr 转换为字符串?
【发布时间】:2012-01-11 20:18:05
【问题描述】:

我有以下内容,它生成了一个 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。我也尝试过使用xmlNodeListGetStringxmlDocDumpFormatMemory,但我无法让它们中的任何一个工作。非常感谢如何从节点转换为字符串的示例,谢谢。

【问题讨论】:

标签: c++ xml string libxml2


【解决方案1】:

关键是添加:

  xmlChar *s;
  int size;

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

  xmlString = (char *)s;
  xmlFree(s);

【讨论】:

    【解决方案2】:

    试试这个例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2013-04-03
      • 2013-09-22
      • 2012-01-04
      • 2013-02-19
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多