在函數中,我使用pugi來首先加載XML文件。然後遍歷樹的子xml節點,並將一些子xml節點(類型爲xml_node的對象)推送到xml_node的向量中。但是,一旦我退出該函數,就會刪除從XML文件加載的原始XML樹結構對象,從而導致xml節點向量中的元素失效。在pugi xml_node中保存PUGI 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根樹對象被刪除後,我也可以在以後安全地解析它們。如何在pugi中做到這一點?
請勿刪除「原始XML根樹對象」。保持活力,使其所有子樹保持活力。 – arayq2