Sample code for 30+ languages & platforms
Unicode C++

Insert XML into existing XML by calling InsertChildTreeAfter

See more XML Examples

Demonstrates how to insert an XML tree or subtree into another XML document using the InsertChildTreeAfter method.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkXmlW.h>

void ChilkatSample(void)
    {
    // Build the 1st XML document:
    // <x1>
    //     <a1>1</a1>
    //     <a2>2</a2>
    //     <a3>3</a3>
    // </x1>

    CkXmlW xml;
    xml.put_Tag(L"x1");
    xml.UpdateChildContent(L"a1",L"1");
    xml.UpdateChildContent(L"a2",L"2");
    xml.UpdateChildContent(L"a3",L"3");

    // Build a 2nd XML document:

    // <x2>
    //   <b1>11</b1>
    //   <b2>22</b2>
    //   <b3>33</b3>
    // </x2>

    CkXmlW xml2;
    xml2.put_Tag(L"x2");
    xml2.UpdateChildContent(L"b1",L"11");
    xml2.UpdateChildContent(L"b2",L"22");
    xml2.UpdateChildContent(L"b3",L"33");

    // We want to insert xml2 into xml to get this:

    // <x1>
    //     <a1>1</a1>
    //     <x2>
    //         <b1>11</b1>
    //         <b2>22</b2>
    //         <b3>33</b3>
    //     </x2>
    //     <a2>2</a2>
    //     <a3>3</a3>
    // </x1>

    // Insert xml2 after "a1"

    int index = xml.TagIndex(L"a1");
    if (index < 0) {
        wprintf(L"a1 not found.\n");
        return;
    }

    xml.InsertChildTreeAfter(index,xml2);

    wprintf(L"%s\n",xml.getXml());

    // The result is:

    // <x1>
    //     <a1>1</a1>
    //     <x2>
    //         <b1>11</b1>
    //         <b2>22</b2>
    //         <b3>33</b3>
    //     </x2>
    //     <a2>2</a2>
    //     <a3>3</a3>
    // </x1>

    // Note: xml2 now points to the subtree within xml.
    // For example, update "b3" and then see how it's updated within the merged document:
    xml2.UpdateChildContent(L"b3",L"33333333");

    wprintf(L"%s\n",xml.getXml());

    // The result:

    // <x1>
    //     <a1>1</a1>
    //     <x2>
    //         <b1>11</b1>
    //         <b2>22</b2>
    //         <b3>33333333</b3>
    //     </x2>
    //     <a2>2</a2>
    //     <a3>3</a3>
    // </x1>
    }