问题
I am using tinyxml.
How do I duplicate or create a copy of an existing XMLDocument?
http://www.grinninglizard.com/tinyxmldocs/classTiXmlDocument.html#a4e8c1498a76dcde7191c683e1220882
I went through this link that says using Clone to replicate a node. But this is protected and I do not want to go for deriving a class out of this and the like.
I also do not want to save the existing XMLDocument to a file and then making another XMLDocument object read the file to have a copy of it.
I am also not able to perform a deep copy using memcpy because I am unaware of the size of the entire XML.
I also do not want to having two objects being used one after the other like:
XMLDocumentObj1 = add_some_data
XMLDocumentObj2 = add_the_same_data, and so on
The primary reason I want a second copy is that, the first might be modified by different sections of the code, while the same copy is being 'read' at multiple places. I need to ensure that there occur no errors when XMLDocument is read, because there are chances that this might have been modified in the background by a running thread, and I get no program crashes.
回答1:
Here is something I wrote to do a deep copy. It takes the source node and copies it under the destination node, children and all. Memory is taken from the destination node's context. Hopefully, it's a start in the right direction for you.
void CopyNode(tinyxml2::XMLNode *p_dest_parent, const tinyxml2::XMLNode *p_src)
{
// Protect from evil
if (p_dest_parent == NULL || p_src == NULL)
{
return;
}
// Get the document context where new memory will be allocated from
tinyxml2::XMLDocument *p_doc = p_dest_parent->GetDocument();
// Make the copy
tinyxml2::XMLNode *p_copy = p_src->ShallowClone(p_doc);
if (p_copy == NULL)
{
// Error handling required (e.g. throw)
return;
}
// Add this child
p_dest_parent->InsertEndChild(p_copy);
// Add the grandkids
for (const tinyxml2::XMLNode *p_node = p_src->FirstChild(); p_node != NULL; p_node = p_node->NextSibling())
{
CopyNode(p_copy, p_node);
}
}
回答2:
I found this and i think this may help you.
https://github.com/leethomason/tinyxml2/blob/master/xmltest.cpp
const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
XMLDocument doc;
doc.Parse( pub );
XMLDocument clone;
for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
XMLNode* copy = node->ShallowClone( &clone );
clone.InsertEndChild( copy );
}
clone.Print();
int count=0;
const XMLNode* a=clone.FirstChild();
const XMLNode* b=doc.FirstChild();
for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
++count;
XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
}
XMLTest( "Clone and Equal", 4, count );
来源:https://stackoverflow.com/questions/30230111/deep-copy-an-xml-via-tinyxml