Reputation: 1212
In a function, I use pugi to first load an XML file. I then traverse the child xml nodes of the tree and push some of the child xml nodes (objects of type xml_node) to a vector of xml_node. But as soon as I exit this function, the original XML tree structure object loaded from the XML file is deleted causing elements in vector of xml nodes to become invalid.
Below is a sample code(written quickly) to show this:
#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;
}
I therefore need a way to save/copy/clone/move sub-tree's(xml nodes) of my original XML tree such that I can safely parse them at a later point even after the original XML root tree object is deleted. How to do this in pugi ?
Upvotes: 1
Views: 1567
Reputation: 9404
Just pass the ownership of the xml_document object to the caller.
You can either do it by forcing the caller to supply an xml_document object (add a xml_document&
argument to the function), or by returning a shared_ptr<xml_document>
or unique_ptr<xml_document>
from the function alongside the node vector.
Upvotes: 1