Share via


Source: saveDOMsmart.cpp

 

This C/C++ source code performs the following steps:

  1. Creates an XML DOM object (pXMLDom) and sets it to synchronous mode.

  2. Loads an XML string to pXMLDom.

  3. Calls the loadXML method on pXMLDom, specifying the XML data as the following string:

<r>\n<t>top</t>\n<b>bottom</b>\n</r>

  1. Displays the resulting XML DOM in the console window.

  2. Calls the save method on pXMLDom to serialize the DOM content to a file (myData.xml).

C/C++ Source File (saveDOMsmart.cpp)

#include <stdio.h>
#include <tchar.h>
#import <msxml6.dll>

// Macro that calls a COM method returning HRESULT value.
#define CHK_HR(stmt)        do { hr=(stmt); if (FAILED(hr)) goto CleanUp; } while(0)

void saveDOMsmart()
{
    MSXML2::IXMLDOMDocumentPtr pXMLDom = NULL;
    HRESULT hr= pXMLDom.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER);

    if (FAILED(hr)) 
    {
        printf("Failed to instantiate an XML DOM.\n");
        return;
    }

    try
    {
        pXMLDom->async = VARIANT_FALSE;
        pXMLDom->validateOnParse = VARIANT_FALSE;
        pXMLDom->resolveExternals = VARIANT_FALSE;

        if(pXMLDom->loadXML(L"<r>\n<t>top</t>\n<b>bottom</b>\n</r>") == VARIANT_TRUE)
        {
            printf("XML DOM loaded from app:\n%s\n", (LPCSTR)pXMLDom->xml);

            CHK_HR(pXMLDom->save(L"myData.xml"));
            printf("XML DOM saved to myData.xml.\n");
        }
        else
        {
            printf("Failed to load DOM from xml string. %s\n", (LPCSTR)pXMLDom->parseError->Getreason());
        }
    }
    catch (_com_error errorObject)
    {
        printf("Exception thrown, HRESULT: 0x%08x", errorObject.Error());
    }

CleanUp:
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    HRESULT hr = CoInitialize(NULL);
    if(SUCCEEDED(hr))
    {
        saveDOMsmart();
        CoUninitialize();
    }

    return 0;

}

To add the saveDOMsmart source code to the project

  1. Create a new C++ source file. For detailed instructions on how to do this, see Set Up My Visual C++ Project. Name the new file saveDOMsmart.cpp.

  2. Copy the C/C++ source code above and paste it into the source file you just created.

Next, build and run the saveDOMsmart project. The result should be the output shown in the following topic.