在pugi xml_node中保存PUGI XML树的子树

时间:2015-07-20 16:09:35

标签: c++ xml pugixml

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

下面是一个示例代码(快速编写)以显示:

#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做到这一点?

1 个答案:

答案 0 :(得分:1)

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

您可以通过强制调用者提供xml_document对象(向函数添加xml_document&参数),或者从函数中返回shared_ptr<xml_document>unique_ptr<xml_document>来执行此操作。节点向量。