Serializing Your Structs Using XML

Environment: VC++ 5.0-6.0, Win95/98/NT 4.0/2K/XP

Introduction

This article shows how to save a struct into an XML file (using STL), and load it back using Microsoft’s MSXML 3.0 parser. If you have Microsoft’s MSXML 4.0 parser installed, modify the stdafx.h file to use MSXML4 instead of MSXML3. This code can be modified to use a class instead of a struct.

Using the Code

To implement this code in your project, add a call to initialize OLE support by inserting a call to ::AfxOleInit in the application class’ InitInstance function. In my demo, this class is called CSerializeApp.

BOOL CSerializeApp::InitInstance()
{
   AfxEnableControlContainer();

   .
   .
   .

   ::AfxOleInit();

   // Because the dialog has been closed, return FALSE so
   // that we exit the application, rather than start the
   // application's message pump.
   return FALSE;
}

To import the Microsoft XML Parser typelib (OLE type library), add the following lines before the stdafx.h file’s closing #endif. directive.

#import <msxml3.dll> named_guids
using namespace MSXML2;

Replace the 3 in msxml3.dll above with 4 if you have Microsoft’s MSXML 4.0 parser installed. In addition, include the following to the stdafx.h file, right before the #import above:

#include <atlbase.h>         // Needed for CComVariant.

Add the files SerializeXML.cpp/h to your project and modify the structs and function names to suit your needs. Finally, call the save/load functions you added to save/load your structures to XML files. In my demo application, I call everything from BOOL CSerializeDlg::OnInitDialog(), just to test it out.

Points of Interest

Introduction to Using the XML DOM from Visual C++ by Tom Archer.

Downloads


Download demo project – 15 Kb


Download source – 3 Kb

More by Author

Get the Free Newsletter!

Subscribe to Data Insider for top news, trends & analysis

Must Read