How to serialize an object to XML by using Visual C++ .NET or Visual C++ 2005

For a Microsoft Visual C# .NET version of this article, see
815813 .
For a Microsoft Visual Basic .NET version of this article, see
315703 .

IN THIS TASK

Summary

This step-by-step article describes how to serialize an object to XML by using Visual C++ .NET or Visual C++ 2005. You can use this method to persist the state of an object. You can also use this method to clone an object by deserializing the XML back to the new object.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
This article assumes that you are familiar with the following topics:
  • General familiarity with XML
  • General familiarity with Visual C++ .NET or Visual C++ 2005
back to the top

XML Serialization

Serialization is the process of converting an object into a form that can be easily transported. The Microsoft .NET Framework includes powerful objects that can serialize any object to XML. You can do this with the System::Xml::Serialization namespace.

Create a console application that creates an object, and then serializes the state of an object to XML. To do this, follow these steps:
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, click
    New, and then click Project.
  3. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under
    Templates.

    In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

    In Visual Studio 2005, click Visual C++ under Project Types, and then click CLR Console Application under Templates.
  4. In the Name text box, type
    815812.
  5. Switch to Class View. To do this, click Class View on the View menu.
  6. Right-click 815812, point to Add, and then click
    Add Class.
  7. In the Add Class dialog box, click
    Generic C++ Class under Templates, and then click Open.

    Note In Visual Studio 2005, click C++ Class under Templates, and then click Add.
  8. In the Generic C++ Class Wizard, type
    Person in the Class name text box, and then click Finish. The Person class appears as follows:
    #pragma once

    class Person
    {
    public:
    Person(void);
    ~Person(void);
    };
    Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:

    1. Click Project, and then click <ProjectName> Properties.



      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.

    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.

    For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
    To make the Person class a public managed C++ class, add the __gc public keyword before the Person class:
    #pragma once
    __gc public class Person
    {
    public:
    Person(void);
    ~Person(void);
    };
  9. Open the Person.h file.
  10. Use the using directive on the System namespace so that you do not have to qualify declarations from these namespaces later in your code. Paste the following code in the Person.h file:
    using namespace System; // This shortcut avoids you having to type System::String
  11. Add the following three public member variables to the Person class:
        String* firstName;
    String* middleNI;
    String* lastName;
  12. Switch to the Code window for the 815812.CPP file.
  13. Use System.dll and System.XML.dll as follows:
    #include "Person.h"
    #using <System.Dll>
    #using <System.XML.Dll>

  14. Use the using directive on the System::XML and
    System::Xml::Serialization namespaces so that you do not have to qualify declarations from these namespaces later in your code:
    using namespace System;
    using namespace System::Xml;
    using namespace System::Xml::Serialization;
  15. In the void Main function, declare and create an instance of the Person class:
    Person* p = new Person();
  16. Set the properties of the Person object:
        p->firstName = S"Jeff";
    p->middleNI = S"A";
    p->lastName = S"Price";
  17. The Xml::Serialization namespace contains an XmlSerializer class that serializes an object to XML. When you create an instance for the XmlSerializer class, you pass the type of the class that you want to serialize to its constructor:
        XmlSerializer* x = new XmlSerializer(p->GetType());
  18. Use the Serialize method to serialize an object to XML. Serialize is overloaded and can send the output to a TextWriter, a Stream, or an XMLWriter object. You can use the following code to send the output to the console:
        x->Serialize(Console::Out,p);
    Console::WriteLine();
    Console::ReadLine();
back to the top

Complete Code Listing

815812.cpp

// This is the main project file for the Visual C++ application project 
// that is generated by using an Application Wizard.

#include <stdafx.h>
#using <mscorlib.dll>

#include "Person.h"

#using <System.Dll>
#using <System.XML.Dll>
using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;

int _tmain()
{
Person* p = new Person();
p->firstName = S"Jeff";
p->middleNI = S"A";
p->lastName = S"Price";
XmlSerializer* x = new XmlSerializer(p->GetType());

x->Serialize(Console::Out,p);
Console::WriteLine();
Console::ReadLine();
return 0;
}

Person.h

#pragma once
using namespace System;

__gc public class Person
{
public:
Person(void);
~Person(void);
String* firstName;
String* middleNI;
String* lastName;

};
back to the top

Verify That It Works

To verify that your project works, press the CTRL+F5 key combination to run the project. A Person object is created and populated with the values that you typed. This state is serialized to XML. The Console window displays the following:
<?xml version="1.0" encoding="IBM437"?>
<Person xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3
.org/2001/XMLSchema-instance">
<firstName>Jeff</firstName>
<middleNI>A</middleNI>
<lastName>Price</lastName>
</Person>
back to the top

Troubleshooting

The Xml::Serialization::XmlSerializer object performs only shallow serialization. If you want to serialize the private variables of an object or child objects, you must use deep serialization.

back to the top

References

For more information about XML Serialization, visit the following Microsoft Developer Network (MSDN) Web site: back to the top
Propriedades

ID do Artigo: 815812 - Última Revisão: 14 de nov de 2007 - Revisão: 1

Comentários