Click here to Skip to main content
15,881,559 members
Articles / Programming Languages / XML
Article

XML Serialization for Complex Data Types

Rate me:
Please Sign up or sign in to vote.
1.40/5 (2 votes)
6 Sep 20061 min read 36.4K   238   18   2
XML serialization for complex data types including GDI objects, Hashtable, and List.

Introduction

Looking up on Google about XML serialization would give us many links about problems, questions, and other things about it. But nowhere, did I find an article that has it all. So if you are looking at how to serialize hashtables, GDI objects (GraphicsPath, Fonts...), etc., read on.

Background

All the code has been verified under Microsoft FxCop 1.35. If you're not very familiar with XML or serialization, refer to MSDN.

Using the code

An XML file can store any of the following: basic type objects (like DateTime...), GDI objects (GraphicsPath, Font, Pen...), or complex objects (Hashtable ...).

The main serialization operation is is done inside Configuration.cs. All new XML object types are listed in XmlUtility.GetXmlTypes. The Save and Load functions are not very difficult to understand.

You can have a Hashtable of anything (integer, list). Just take a look at the code in the InitDefault function in BasicConfiguration, GdiConfiguration, and OtherConfiguration.

C#
// Main code
try
{
    string           strConfigurationFile = @"./config.XML";
    Configuration    Config = new Configuration ();
    Configuration    Config2;

    // Save configuration file
    Console.WriteLine ("Writing configuration file");
    Config.Save (strConfigurationFile);

    // Assign new values
    Console.WriteLine ("Reset values");
    Config.BasicConfiguration.MyFloat    = 0.0f;
    Config.BasicConfiguration.MyString   =String.Empty;
    Config.BasicConfiguration.MyInt      = 64;

    // Node test
    Console.WriteLine ("Node test");
    XmlNodeContainer ScreenNode = (XmlNodeContainer)
          (Config.OtherConfiguration.XmlNodeContainer["Screen"]);
    XmlKeyAndValue    KeyAndValue1 = (XmlKeyAndValue)ScreenNode["ResolutionX"];
    XmlKeyAndValue    KeyAndValue2 = (XmlKeyAndValue)ScreenNode["ResolutionY"];
    Console.WriteLine (string.Format ("Resolution saved : {0}x{1}", 
                       KeyAndValue1.Value, KeyAndValue2.Value));

    XmlKeyAndValue    KeyAndValue3 = (XmlKeyAndValue)((XmlNodeContainer)
         Config.OtherConfiguration.XmlNodeContainer["Network"])["MAC ADDRESS"];
    Console.WriteLine (string.Format ("Network MAC ADDRESS saved : {0}", 
                                      KeyAndValue3.Value));

    // Reload default values
    Console.WriteLine ("Reload default configuration");
    Config2 = Configuration.Load (strConfigurationFile);
    Console.WriteLine ("Ok");
}
catch (Exception e)
{
    Console.WriteLine ("ERROR");
    Console.WriteLine (e.ToString ());
}

Console.WriteLine ("Press Return to quit");
Console.ReadLine ();

I hope you'll find it useful.

Points of interest

I've tried to make the code as simple as possible so that anyone can upgrade it.

Bug report

There is one 'bug' where I need some help. In xmltranslatorelement.cs (line 111), FxCop returns this error: CollectionPropertiesShouldBeReadOnly. So you'd prolly think that you could remove the set() attribute, but here comes the trouble. We must implement the Add and GetEnumerator functions from IEnumerable but we have a hashtable. If someone knows how to break this error...

History

  • 2006-09-05
    • First version.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralXmlSerialization Pin
HRThomann24-Sep-06 21:24
HRThomann24-Sep-06 21:24 
I have used custom conversion operators in this context, see my SerializableColor class below.

public class SerializableColor
{
public SerializableColor() { }
///
/// Constructor from PowerPoint.ColorFormat
///

/// <param name="color" />
public SerializableColor(PowerPoint.ColorFormat color)
{
System.Drawing.Color temp = System.Drawing.Color.FromArgb(color.RGB);
A = 255;
R = temp.B;
G = temp.G;
B = temp.R;
}
///
/// Constructor from System.Drawing.Color
///

/// <param name="color" />
public SerializableColor(System.Drawing.Color color)
{
A = color.A;
R = color.R;
G = color.G;
B = color.B;
}
///
/// Explicit conversion operator from System.Drawing.Color
///

/// <param name="font" />
/// <returns>
public static implicit operator SerializableColor(System.Drawing.Color color) { return new SerializableColor(color); }
///
/// Explicit conversion operator to System.Drawing.Color
///

/// <param name="font" />
/// <returns>
public static implicit operator System.Drawing.Color(SerializableColor color) { return System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B); }

public static System.Drawing.Color operator |(System.Drawing.Color a, SerializableColor b)
{
return ((b == null) ? a : (System.Drawing.Color)b);
}

public byte A;
public byte R;
public byte G;
public byte B;
}

Hans-Rudolf Thomann
GeneralRead Only Pin
ByteGhost6-Sep-06 14:52
ByteGhost6-Sep-06 14:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.