c++ - 在 pugi xml_node 中保存 PUGI XML 树的子树

标签 c++ xml pugixml

在一个函数中,我使用 pugi 首先加载一个 XML 文件。然后,我遍历树的子 xml 节点,并将一些子 xml 节点(xml_node 类型的对象)推送到 xml_node 的 vector 。但是一旦我退出这个函数,从 XML 文件加载的原始 XML 树结构对象就会被删除,导致 xml 节点 vector 中的元素变得无效。

下面是一个示例代码(快速编写)来展示这一点:

#include "pugixml.hpp"
#include <vector>

void ProcessXmlDeferred(  std::vector<pugi::xml_node> const &subTrees )
{
   for( auto & const node: subTrees)
   {
       // parse each xml_node node
   }
}

void IntermedProcXml( pugi::xml_node const &node)
{
   // parse node
}

std::vector<pugi::xml_node> BuildSubTrees(pugi::xml_node const & node )
{
  std::vector<pugi::xml_node> subTrees;

  pugi::xml_node temp = node.child("L1");
  subTrees.push_back( temp );

  temp = node.child.child("L2");
  subTrees.push_back( temp );

  temp = node.child.child.child("L3");
  subTrees.push_back( temp );

  return subTrees;
}

void LoadAndProcessDoc( const char* fileNameWithPath, std::vector<pugi::xml_node> & subTrees )
{
    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load( fileNameWithPath );

    subTrees = BuildSubTrees( result.child("TOP") );
    IntermedProcXml( result.child("CENTRE") );

    // Local pugi objects("doc" and "result") destroyed at exit of this 
    // function invalidating contents of xml nodes inside vector "subTrees"
}


int main()
{
    char fileName[] = "myFile.xml";
    std::vector<pugi::xml_node> myXmlSubTrees;  

    // Load XML file and return vector of XML sub-tree's for later parsing
    LoadAndProcessDoc( fileName, myXmlSubTrees );

    // At this point, the contents of xml node's inside the vector  
    // "myXmlSubTrees" are no longer valid and thus are unsafe to use

    // ....
    // Lots of intermediate code
    // ....

    // This function tries to process vector whose xml nodes 
    // are invalid and thus throws errors
    ProcessXmlDeferred( myXmlSubTrees );

    return 0;
}

因此,我需要一种方法来保存/复制/克隆/移动原始 XML 树的子树(xml 节点),这样即使在原始 XML 根树对象之后,我也可以在以后安全地解析它们被删除。如何在 pugi 中执行此操作?

最佳答案

只需将 xml_document 对象的所有权传递给调用者即可。

您可以通过强制调用者提供 xml_document 对象(向函数添加 xml_document& 参数)或返回 shared_ptr<xml_document> 来实现。或 unique_ptr<xml_document>来自节点 vector 旁边的函数。

关于c++ - 在 pugi xml_node 中保存 PUGI XML 树的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521293/

相关文章:

Android - 修改 XML 中的布局值

c++ - 有效的字符数组(这是一个有效的字符串)

java - 如何在 Wildfly 中为 LDAP 扩展模块启用调试日志记录

c++ - Mongoose 网络库 : how to get authenticated user?

java - 时间表 Android 应用程序无法运行

c++ - PugiXML 从递归 xml_tree_walker 中提取数据

c++ - 使用 PugiXML 进行 XML 解析,无限循环

c++ - pugixml 解析器获取元素值

c++ - 我可以定义一个环境变量并在条件编译中使用它吗?

c++ - 在所有方向上移动矩阵列/行 C++