1

関数では、最初に 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 ノード) を保存/コピー/クローン/移動する方法が必要です。プギでこれを行う方法は?

4

1 に答える 1