#include <stdio.h> #import <msxml5.dll> using namespace MSXML2; void main() { IXMLDOMDocument3Ptr domFree=NULL; IXMLDOMDocument3Ptr domApt =NULL; IXMLDOMNodePtr node =NULL; IXMLDOMNodePtr clone =NULL; CoInitialize(NULL); if (FAILED(domFree.CreateInstance(__uuidof(FreeThreadedDOMDocument50)))) { printf("Can't create domFree\n"); return ; } if (FAILED(domApt.CreateInstance(__uuidof(DOMDocument50)))) { printf("Can't create domApt\n"); return ; } domApt->async = VARIANT_FALSE; if (VARIANT_FALSE == domApt->load("doc1.xml")) { printf("Can't load doc1.xml\n"); return; } domFree->async = VARIANT_TRUE; if (VARIANT_FALSE == domFree->load("doc2.xml")) { printf("Can't load doc2.xml\n"); return; } // Copy a node from domFree to domApt: // Fetch the "/doc" (node) from domFree (doc2.xml). // Clone node for import to domApt. // Append clone to domApt (doc1.xml). // node = domFree->selectSingleNode("/doc"); if (NULL == node) { printf("Can't fetch /doc from domFree\n"); return; } clone = domApt->importNode(node, VARIANT_TRUE); if (NULL == clone) { printf("Can't clone /doc from doc2.xml\n"); return; } domApt->documentElement->appendChild(clone); domApt->documentElement->appendChild(domApt->createTextNode("\n")); printf("doc1.xml after importing /doc from doc2.xml:\n"); printf(domApt->xml); printf("\n"); node.Release(); node = NULL; clone.Release(); clone = NULL; // Clone a node using importNode() and append it to the same DOM: // Fetch the "doc/b" (node) from domApt (doc1.xml). // Clone node using importNode on domApt. // Append clone to domApt (doc1.xml). // node = domApt->selectSingleNode("/doc/b"); if (NULL == node) { printf("Can't fetch /doc/b from domApt\n"); return; } clone = domApt->importNode(node, VARIANT_TRUE); if (NULL == clone) { printf("Can't clone /doc/b from doc1.xml\n"); return; } domApt->documentElement->appendChild(domApt->createTextNode("\t")); domApt->documentElement->appendChild(clone); printf("doc1.xml after importing /doc/b from self:\n"); printf(domApt->xml); printf("\n"); node.Release(); node = NULL; clone.Release(); clone = NULL; // Clone a node and append it to the dom using cloneNode(): // 1. Fetch "doc/a" (node) from domApt (doc1.xml). // 1. Clone node using cloneNode on domApt. // 2. Append clone to domApt (doc1.xml). // node = domApt->selectSingleNode("/doc/a"); if (NULL == node) { printf("Can't fetch /doc/a from domApt\n"); return; } clone = node->cloneNode(VARIANT_TRUE); if (NULL == clone) { printf("Can't clone /doc/a from doc1.xml\n"); return; } domApt->documentElement->appendChild(clone); printf("doc1.xml after cloning /doc/a from self:\n"); printf(domApt->xml); printf("\n"); node.Release(); node = NULL; clone.Release(); clone = NULL; domApt->save("out.xml"); printf("a new document was saved to out.xml in the current working directory.\n"); domApt.Release(); domFree.Release(); CoUninitialize(); }
Try It!
Note You can also copy the file into the project's main directory using Windows Explorer (or a command prompt).