XML Serialization for MFC

The native object serialization offered by MFC (CArchive, CObject::Serialize) has several disadvantages. The major disadvantages result from the fact that it is a binary serialization. This results in:

  1. Non-robustness—your program will probably crash if you read an archive produced by another version of your program. This can be avoided by complex and unwieldly version management. By using XML, this can be largely avoided.
  2. Heavy dependencies between your program object model and the archived data. Change the program model and it is almost impossible to read data from a previous version.
  3. Archived data cannot be edited, understood, and changed, except with the associated application.
  4. Archived data cannot be exchanged across platforms.
  5. Application configuration data can be generated by other tools in XML that can be directly imported by your application.

However, it has one major advantage; it is easy to use.

I have tried to remove the disadvantages by serializing objects to XML, and retaining the ease of use. It's enough to use the various macros in your Serialize method. For example, consider the following code:

// .h file
class CSomeClass : public CObject
{
public:
  CSomeClass();
  DECLARE_XMLSERIAL(CSomeClass)

// Attributes
public:
  enum {eFIRST, eSECOND} m_enumAttribute;
  int     m_intAttribute;
  bool    m_boolAttribute;
  CString m_stringAttribute;

// Operations
  virtual void Serialize(CArchive& ar);

}

// .cpp file
IMPLEMENT_XMLSERIAL(CSomeClass, CObject)

void CSomeClass::Serialize(CArchive& ar)
{
   XMLCLASSNODE
   XMLINTDATA(m_enumAttribute);
   XMLDATA(m_intAttribute);
   XMLDATA(m_boolAttribute);
   XMLDATA(m_stringAttribute);
   ENDNODE
}

Follow these steps to use in a standard MFC application (see sample project):

  1. Include the files XMLArchive.cpp and XMLArchive.hpp into your project.
  2. Copy the supplied stdafx.h fragment into your stdafx.h.
  3. Override your CDocument derived class's OnSaveDocument to use CXMLArchive instead of the normal CArchive.
  4. Enclose your Serialize methods with the macros XMLCLASSNODE and XMLENDNODE. Within this block, use the XMLDATA to serialize your attributes. Use XMLINDATA for enums (it casts them to int). Call any base class Serialize method from within the XMLCLASSNODE, XMLENDNODE block.

Use the application to create a new document and save it to disk. Use Internet explorer or XML Notepad to examine the contents of the file. You will se the application's object model preserved in XML.

Use the debugger to verify that the file is reloaded correctly when opening the file.

This method of serialization can serialize complex object models, but objects that are referenced n times are serialized n times and not only once. So, try to avoid multiple object references.

Downloads

Download demo project - 33 Kb
Download source - 6 Kb