Archived Forum Post

Index of archived forum posts

Question:

Merging XML files at a particular node

Jun 08 '12 at 18:01

I have two xml documents, each contain a <contents></contents> node, I would like to append the <contents> items from one document to the other.

What would be the recommended way of accomplishing this using CkXml?

Thanks!


Answer

Trying to figure out how to post code snippets using this friggin markdown...


Answer

void xmlMergeTest(void)
{
CkXml xml1;
// This file may be downloaded from http://www.chilkatsoft.com/data/plants1.xml
xml1.LoadXmlFile("c:/aaworkarea/plants1.xml");

CkXml xml2;
// This file may be downloaded from http://www.chilkatsoft.com/data/plants2.xml
xml2.LoadXmlFile("c:/aaworkarea/plants2.xml");

// Merge the children of the "Contents" node in xml2 to xml1.
// The children are moved (not copied) so that afterwards the xml2 document (in memory)
// will no longer have the children.  The files remain the same unless the XML is saved..

// Find the "Contents" node of each:
CkXml *c1 = xml1.FindChild("Contents");
CkXml *c2 = xml2.FindChild("Contents");

// Move each child sub-tree from xml2 to xml1
int n = c2->get_NumChildren();
int i;

for (i=0; i<n; i++)
    {
    // We always get the 1st child because each time it is moved,
    // the next child is at index 0.
    CkXml *child = c2->GetChild(0);
    c1->AddChildTree(child);
    // (Remember, deleting a CkXml object is simply deleting a reference to 
    // a node in the XML document.  The node within the XML document is not deleted.)
    delete child;
    }

delete c1;
delete c2;

xml1.SaveXml("c:/aaworkarea/merged.xml");
xml2.SaveXml("c:/aaworkarea/gutted.xml");

return;
}