Click here to Skip to main content
Click here to Skip to main content

XML Serialization in .NET

By , 26 Jul 2002
 

Sample Image

Introduction

My previous article, Hash Table and Serialization in .NET, describes how the content of a hash table is serialized to and deserialized from a binary file. This article continues the serialization topic, and describes XML serialization in .NET, where objects are serialized and deserialized into and from XML documents.

XML serialization implemented by XMLSerializer class converts an object's public classes, properties and fields to a serial XML format. The following example shows how an object of the Person class is serialized into a XML document.

class Person
{
   public Person( string firstName, string lastName )
   {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   public string firstName;
   public string lastName;
}   

static void Main()
{
   Person person = new Person( "John", "Doe" );

   XmlSerializer x = new XmlSerializer( typeof(Person) );
   TextWriter writer = new StreamWriter( "person.xml" );
   x.Serialize( writer, person );
}

If you run the above example, you will get a runtime error mesage, System.InvalidOperationException. The error is caused by the line XmlSerializer x = new XmlSerializer( typeof(Person) );. As it turns out the class Person requires a modifier public and a default constructor. These are common mistakes that I made while working with XmlSerializer class. After you add the public modifier and the default constructor to the Person class, you will get the following XML elements.

<?xml version="1.0 encoding="utf-8"?>
<Person xmlns:xsd="http:www.w3.org/2001/XMLScheme"
        xmlns:xsi="http:www.w3.org/2001/XMLScheme-instance">
    <firstName>John</firstName>
    <lastName>Doe</lastName>
</Person>

As you can see, the element names in the above XML document reflect the public member variable names. You may ask what if I want to make the member variables private. Can I still serialize this class?. XmlSerializer cannot serialize private members, however, you can use public properties as the access methods to the private members as shown below.

   public string FirstName
   {
      get { return firstName; }
      set { firstName = value; }
   }

   public string LastName
   {
      get { return lastName; }
      set { lastName = value; }
   }

   private string firstName;
   private string lastName;

In this case, the XML elements would be FirstName and LastName instead of firstname and lastname respectively to reflect the property names. You can change the XML element names, so that they are different from the property names by using C# attributes. For example, if you want to change the FirstName element to MyFirstName, you can add the following XML element attribute to the FirstName property.

[XmlElement(ElementName = "MyFirstName")]
public string FirstName
{
   get { return firstName; }
   set { firstName = value; }
}

Now, let's expand on the above concept to a more complex application such as a phone book application as described in my previous article, Hash Table and Serialization in .NET. The following UML class diagram shows the relationships between classes that are part of the application. The Contacts class contains one or more Contact, and Contact class contains a Person class and a PhoneNumber class.

UML Diagram

The Person, PhoneNumber, and Contact classes are straight forward and self explanatory, so I will not go into details of these classes. The Contacts class has a private hash table member variable table that takes the Person object as the key and the Contact object as the value. Since this hash table member variable contains all of the contacts, it will be nice if it can be serialized directly to a XML document. However, as it turns out, XmlSerializer does not work with the Hashtable class because the Hashtable indexer takes a non-integer parameter (object parameter), and XmlSerializer expects indexers with only an integer parameter. So in order to serialize all of the contacts to the XML document, the hash table is converted to a Contact array, and this array is then serialized to a XML document as shown below.

// Create an instance of Contact array, and copy the content of 
// the hash table to this array
Contact[] aContact = new Contact[table.Count];
table.Values.CopyTo( aContact, 0 );

// Deserialize the content of the Contact array to a XML file
XmlSerializer x = new XmlSerializer( typeof(Contact[]) );
TextWriter writer = new StreamWriter( "phonebook.xml" );
x.Serialize( writer, aContact );

To deserialize the XML elements from the XML document to the hash table, the above steps will be reversed. The XML elements are first deserialize to a Contact array, and then each member of the array is added to the hash table as follows.

// Create an instance of the XmlSerializer class of type Contact array 
XmlSerializer x = new XmlSerializer( typeof(Contact[]) );

// Read the XML file if it exists ---
FileStream fs = null;
try
{
   fs = new FileStream( "phonebook.xml", FileMode.Open );

   // Deserialize the content of the XML file to a Contact array 
   // utilizing XMLReader
   XmlReader reader = new XmlTextReader(fs);         
   Contact[] contacts = (Contact[]) x.Deserialize( reader );

   // Add each member of the Contact array to the hash table
   for ( int i = 0; i < contacts.Length; i++ )
   {
      Contact contact = (Contact) contacts[i];
      table.Add( contact.GetPerson, contact );
   }
}
catch( FileNotFoundException )
{
   // Do nothing if the file does not exists
}
finally
{
   if ( fs != null ) fs.Close();
}

That is all for now. I hope you enjoy this brief introduction on XML serialization in .NET.

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

About the Author

Liong Ng
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to Serialize [CDATA] node using XMLSerializermemberghorpade.sangram11 Dec '07 - 2:21 
<Hi,
I can able to add the CDATA section inside the xml string but when i go to serialize it, it is converting the opening "<" to < which does not understand by the server as
for C++ (Xerces)and java(jaxb) doing it correctly.
 
The request string with CDATA before serializing is as

<body><bodystring><![CDATA[<xml version="1.0" encoding="utf-8">GroupMember]]></bodystring></body>
 
The request String after passing to XMLSerializer is as follows, which change the CDATA node tag which leads to DOM parsing exception.
 
<body><bodystring><![CDATA[<?xml version="1.0" encoding="utf-8"?><InitTypeByNamesInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://abc.com/Schemas/Internal/Core/2006-03/Types"><typeNames>GroupMember</typeNames></InitTypeByNamesInput>]]></bodystring></body>

 
Can anybody help me how i can preserve the <![CDATA] node as it is so that my server can understand the request?
 

Thanks in advance.
Sangram.]]></bodystring></body>
Questionserializing a System.Windows.Forms.Button Classmemberankur.ag198124 Jul '06 - 21:32 
Hi ,
 
using the same teqniue i tried serialzing a variable of System.Windows.Fomrs.Button class. But it throws an error-
 

Error reflecting System.Windows.Froms.Button
 
Please tell me how to do this
 
Thanks
ankur
 
Ankur Agarwal

QuestionAny plans to upgrade to 2.0?memberwws3580111 Feb '06 - 19:15 
I have just started using 2.0 and it seems to have enhanced the handling of enumerators. Do you plan to upgrade?
Generalcommentsmemberadras17 Jan '06 - 21:56 
is it possible to serialize xml comments, too? Because i want to convert one file to xml. the source file includes comments, and after i convert them, it would be cool if they would be present as xml comments
GeneralXML Serialization in which a variable name can be assigned to ElementNamememberSnehal Ganjigatti22 Jul '05 - 10:15 
Hi,
 
I am working on a C# application that allows the user to draw a diagram and save it in XML format.
The following line,
[XmlElement(ElementName = "hello")],
allows me to assign a particular string as an Element name.
But I want the element name to be equal to a variable, that gets assigned a string value when I save the diagram.
So, I was wondering if there is any way that I can assign the variable name to 'ElementName' ?
Please let me know.
 
Thanks,
Snehal
GeneralDouble array serializedmemberExnor1 Jun '05 - 3:05 
I have a bit of a issue with the class that I need to serialize... can anybody help?
 
public class Bane
{
///
/// Navnet på banen
///

public string navn;
///
/// Størrelsen på hele banen
///

//[NonSerialized]
const int WIDTH = 700;
//[NonSerialized]
const int HEIGHT = 440;
///
/// Indeholder den retangel som er banens ydre kant
///

//[NonSerialized]
public GraphicsPath gp;
///
/// Startretningen for slangen
///

public Retning startRetning;
///
/// Startpunktet for slangen
///

public Point startPoint;
///
/// Skal indeholde Point arrays for hver sæt a vægge.
///

public Point[][] vaegge;
//[NonSerialized]
public PointStatus[,] net;

public Bane(Point[][] vaegge, Point startPoint, Retning startRetning, string navn)
{
this.gp = new GraphicsPath();
this.gp.AddRectangle(new Rectangle(0,0,WIDTH,HEIGHT));
 
this.navn = navn;
this.startRetning = startRetning;
this.startPoint = startPoint;
this.vaegge = vaegge;
 
ResetBane();
}
 
I've tried several solutions, but none seems to be able to handle the double array or my Enum 'Retning'
Generaldeserializationmembersomiali9 Oct '03 - 7:15 
iam trying to deserialize a xml file into an array of class objeccts in c#
here is thecodei use:
using System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Diagnostics;
 
[XmlRoot("Mapping")]
public class Mapping
{
[XmlElement("tag")]
public string tag;
[XmlElement("url")]
public string url;
 
public Mapping(){}

public Mapping(string tag,string url)
{
this.tag=tag;
this.url=url;
}
}
 
public class Reader
{
public static void Main(string[] arg)
{
// Create an instance of the XmlSerializer class of type Contact array
XmlSerializer x = new XmlSerializer( typeof(Mapping[]) );
 
// Read the XML file if it exists ---
FileStream fs = null;
Mapping[] mappings=null;
try
{
fs = new FileStream( "mappingfile.xml", FileMode.Open );
 
// Deserialize the content of the XML file to a Contact array
// utilizing XMLReader
XmlReader reader = new XmlTextReader(fs);
mappings = (Mapping[]) x.Deserialize( reader );
}
catch( FileNotFoundException )
{
Console.WriteLine("The file does not exist!!");
}
finally
{
if(mappings != null)
{
for(int i=0;i<mappings.Length;i++)
{
if(mappings[i].tag == "213")
{
string urlRetrieved = mappings[i].url;
ProcessStartInfo info = new ProcessStartInfo(urlRetrieved);
info.Verb="open";
Process.Start(info);
}
}
}
 
if ( fs != null ) fs.Close();
}
}
}
 
Here the xml file:

<Mapping xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
213
www.cs.purdue.edu
</Mapping>
 
i get an exception InvalidOperationExcpetion frm the line
"mappings = (Mapping[]) x.Deserialize( reader );
saying that there was an error in teh xml document
can someone tell me what iam doing wrong?
thanks
sumaira
GeneralSerializing XmlSchema Arraymembermanij28 Jul '03 - 4:49 
I have array of XmlSchema (XmlSchema[]), plz see below:
 
I could able to serialize using XmlSerializer as below:
 
----
----
XmlSerializer theSerializer = new XmlSerializer(typeof(XmlSchema[]));
TextWriter writer = new StreamWriter("SchemaCollection.xml");
theSerializer.Serialize(writer, xmlSchemaArray); //XmlSchema[] object
writer.Close();

 
However, i could not able to de-serialize this. I tried with following code:
 
FileStream fs = new FileStream("SchemaCollection.xml", FileMode.Open);
XmlReader reader = new XmlTextReader(fs);
if (theSerializer.CanDeserialize(reader))
{
xmlSchemaArray = (XmlSchema[])theSerializer.Deserialize(reader);
}
reader.Close();

 
This above code is not working. The XmlSchemaArray is blank!!!
 
Can any one tell me what is going wrong??? I already spent my whole weekend with this problem. Please help me..
 


GeneralSerializing Objects within objectsmemberJustin Armstrong30 Jun '03 - 9:47 
I can't seem to find any examples of how to serialize objects that have user-defined objects within them. For example:
 
public class BankAccount
{
public int accountNumber;
public float balance;
}
 
public class Person
{
public int id;
public string name;
 
public BankAccount account;
}
 

Now, what XML tags ([XmlAttribute] / [XmlElement]) do I need to add to these classes in order to be able to serialize Person objects?

GeneralRe: Serializing Objects within objectseditorHeath Stewart30 Jun '03 - 11:15 
Use XmlElement and XmlAttribute anywhere you want. I recomment using XmlElement on non-intrinsic properties (where as you put XmlRoot on the class itself, but the prop attribute overrides). Basically, you do whatever you want. The XmlSerialier (or any serializer that's written correctly) will serialize an entire object graph, as serializers are supposed to.
 
Here's what I recommend:
[XmlRoot("bankAccount")]
public class BankAccount
{
[XmlAttribute("accountNumber")]
public int accountNumber;
 
[XmlAttribute("balance")]
public float balance;
}
 
[XmlRoot("person")]
public class Person
{
[XmlAttribute("id")]
public int id;
 
[XmlAttribute("name")]
public string name;
 
[XmlElement("account")]
public BankAccount account;
}

 

Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN

GeneralRe: Serializing Objects within objectsmemberJustin Armstrong2 Jul '03 - 13:25 
This is what I've been trying so far:
----------------------------------------
[XmlRootAttribute(Namespace="Bank", ElementName = "BankAccount", IsNullable = false)]
public class BankAccount
{
[XmlElement(DataType = "int")]
public int accountNumber;
[XmlElement(DataType = "float")]
public float balance;
 
public serializeMe(StreamWriter writer)
{
XmlSerializer xmls = new XmlSerializer(typeof(BankAccount));
xmls.Serialize(writer, this);
}
 
}
 
public class Person
{
[XmlElement(DataType = "int")]
public int id;
[XmlElement(DataType = "string")]
public string name;
[ ??? ]
public BankAccount account;
 

public serializeMe(StreamWriter writer)
{
XmlSerializer xmls = new XmlSerializer(typeof(Person));
xmls.Serialize(writer, this);
}
}
----------------------------------------
And, with this, everything has worked fine, except for BankAccount within the Person class.
 
In theory, if the BankAccount object is serializable, can I serialze it as an XmlElement tag? If so, what do type do I assign it as?!
 
I've also tried using the XmlAttribute tag for the BankAccount object, but when I serialize a Person object, nothing shows up in the serialized file.
(e.g.
[XmlAttribute("BankAccount")]
public BankAccount account;
)
 

I know I'm still missing something, but what is it? I'm coding blind. Please help!
GeneralRe: Serializing Objects within objectseditorHeath Stewart2 Jul '03 - 18:06 
First, don't use the DataType property in your XML attributes, especially if you're just reiterating what's already apparent: an int is an int, and a float is a float. Trust me, the system knows!
 
If you use the code I gave you, all should work well. I've done this many times and it is quite simple. Give it a try and, again, don't use the DataType unless you need to persist something differently that what it's type (either through intrinsic rules or inherited from the Type's XML serialization attributes) declares.
 
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN

GeneralRe: Serializing Objects within objectsmemberJustin Armstrong3 Jul '03 - 6:49 
Ok, I've got everything being serialized, but now I've run into a problem with deserializing.
 
In the actual code I'm using, not just the simple BankAccount/Person example, I have many objects that need to be serialized. The problem seems to be that using the code given in this tutorial, each time I serialize an object, it creates a new top-level element. Now, I could put each object's XML data into a new file, but that seems silly. Given the large number of objects I have, I would like to put it all into one file. What do I need to do in order to accomplish this, given the code used in this tutorial as a starting point.
 
Thanks!
GeneralRe: Serializing Objects within objectseditorHeath Stewart3 Jul '03 - 8:47 
You don't have to serialize to a file. You can serialize to any Stream, including a MemoryStream. Serialize to a few of those, then read through each stream and add the content to a parent node that is a FileStrea or something (persistent to a file).
 
 
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN

GeneralRe: Serializing Objects within objectsmemberJustin Armstrong3 Jul '03 - 10:39 
Yes, this is what I am having problems with. How do I "add the content to a parent node that is a File Stream" ? I assume I need to use something like a XmlWriter object?
GeneralRe: Serializing Objects within objectseditorHeath Stewart3 Jul '03 - 10:59 
Right. Serialize each object to a MemoryStream, then use an XmlTextReader (or do it raw) to read each MemoryStream and save it to an XmlTextWriter that uses a FileStream for persistence. There are examples in the .NET Framework SDK docs.
 
 
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN

GeneralRe: Serializing Objects within objectsmemberJustin Armstrong4 Jul '03 - 8:03 
Ok, here's what I'm trying:
----------------------------------------------------
Stream stream = null;
MemoryStream mStream1 = new MemoryStream();
MemoryStream mStream2 = new MemoryStream();

XmlTextReader xmltr1 = null;
XmlTextReader xmltr2 = null;
XmlTextWriter xmltw = null;
 
StreamWriter writer = null;
 
if((stream = saveFileDialog.OpenFile()) != null)
{
// File stream
writer = new StreamWriter(stream);
 
// Collect XML data
constants.SerializeObject(mStream1);
vehicleManager.serializeVehicles(mStream2);
 
xmltr1 = new XmlTextReader(mStream1);
xmltr2 = new XmlTextReader(mStream2);
xmltw = new XmlTextWriter(stream,Encoding.ASCII);
 

xmltw.WriteStartDocument();
xmltw.WriteStartElement("Bank");
xmltw.WriteEndElement();
 
xmltr1.MoveToFirstAttribute();
xmltr1.Read();
xmltw.WriteRaw(xmltr1.Value);
 
xmltr1.MoveToNextAttribute();
xmltr1.Read();
xmltw.WriteRaw(xmltr1.Value);
 
xmltw.WriteEndElement();
xmltw.WriteEndDocument();
 
xmltw.Flush();
 
writer.Close();
}
.
.
.
------------------------------------------------------
 
I can't seem to find any specific examples in the SDK docs or elsewhere on this. Am I sort of on the right track, or not even close?
 
With this method, so far I seem to be running into a problem of not having a root element. That's what I thought I was creating with the WriteStartElement("Bank") call. Am I wrong?
 
Basically, the problem is that the memory streams each contain complete XML documents on their own, complete with headers and all. So, if I just try to smoosh them together in one file, there ends up being multiple headers and multiple top-level elements.
 
I assume this means that I need to use an XMLReader to parse through the XML structures in the memory streams and pluck out the elements within, then in turn, to put these elements inside a new XML structure I'm building (perhaps using WriteRaw()) using the XmlTextWriter. Does that sound correct? If so, where am, I going wrong?
 
Thanks for the help, by the way! It's very much appreciated.

GeneralRe: Serializing Objects within objectseditorHeath Stewart7 Jul '03 - 2:15 
First of all, did you read the documentation for XmlTextWriter.WriteStartElement()? If you had, you wouldn't even be asking me that question: never forget about reading documentation - you'll never learn if you only guess. There's even a simple example in there. You're not getting a root because you're trying to write multiple roots - I'm surprised you're not getting an exception.
 
Second, while are you calling XmlTextReader.MoveToNextAttribute()? You do know the difference between attributes and elements, right? You don't want attributes - you want the whole element. XmlTextReader.Value isn't good either - it only gets you the normalized text for the element - not the XML document that you want to treat as a fragment.
 
Since the XmlTextReader should be positioned at the root element of the serialized graph, use XmlTextReader.ReadOuterXml. Read the docs though, so that you know exactly what it does. Reading the docs (i.e., researching) is half of programming - at least.
 
 
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN

GeneralRe: Serializing Objects within objectsmemberJustin Armstrong8 Jul '03 - 6:40 
For anyone out there actually looking for examples, here is the solution I used. I'm sure there are other ways, however.
 
One important thing to note is that you can't use the same XMLSerializer for serializing or deserializing different types. That is, you need a new serializer object for each object type that you are deserializing.
 
This is the XML file I was working with:
 

<xml...?>
<global>
<ObjectOfType1>
<name>blah</name>
.
.
.
</ObjectOfType1>
<ArrayOfObjectOfType2>
<ObjectOfType2>
<name>blah</name>
.
.
.
</ObjectOfType2>
<ObjectOfType2>
<name>blah</name>
.
.
.
</ObjectOfType2>
.
.
.
</ArrayOfObjectOfType2>
<global>

 

Now, here's the snippet that deserialized it (note that error checking and some declarations are ommitted):
 

fs = new FileStream(openFileDialog.FileName,FileMode.Open);
XmlTextReader xmlr = new XmlTextReader(fs);
 
xmlr.ReadStartElement();

// Read past first
xmlr.ReadInnerXml();
 
XmlSerializer xmls = new XmlSerializer(typeof(ObjectOfType1));
ObjectOfType1 o1 = (ObjectOfType1)xmls.Deserialize(xmlr);
 
XmlSerializer xmls2 = new XmlSerializer(typeof(ObjectOfType2[]));
(ObjectOfType2[])list.ToArray(typeof(ObjectOfType2));
 
ObjectOfType2[] arrayO2 = (ObjectOfType2[])xmls2.Deserialize(xmlr);

 
This seems to work well, albeit a little slowly. Please let me know if you find a better way.
GeneralRTF stringmemberlerede22 Jun '03 - 21:09 
If the string is of RTF type don't deserialize it Frown | :( . Suggestions ?

GeneralSerializing ArrayList of ArrayListsmemberAaron R>18 Jun '03 - 6:55 
I am trying to figure out how to serialize an ArrayList that contains other ArrayLists. The sub arrayLists all hold the same type of object.
 
IE -
 
alist1
   sublist1
      myObject1
      myObject2
   sublist2
      myObject3
      myObject4
      myObject5
 
I know how to serialize an ArrayList out, even if it has different objects in it.
 
Any help would be greatly appreciated!
 
Regards,
Aaron R>
GeneralRe: Serializing ArrayList of ArrayListsmemberLiong28 Jun '03 - 11:25 
You cannot serialize the ArrayList objects directly. Your class needs to implement the ICollection interface, and in your class you can have an ArrayList member variable. You need to implement an "Add" method and an "Item" property in order to be serialized. Also you must implement the ICollection methods as shown below,
 
Class FooList : ICollection
{
//--- list may contain list of Foo ---
private ArrayList list = new ArrayList;
 
//--- Implement the "Add" and "Item" methods ---
//--- Implement ICollection methods ---
}
 
Class Foe
{
//--- fooList is one of the member variables ---
private FooList fooList = new FooList();
 
//--- Implement the fooList property ---
}
 
Hope it helps.
 
Liong

Generalhelp with serializationmemberbaby.chai26 Mar '03 - 8:46 
Hi!
This article was great. I was just wondering if it's possible to serialize recursively...
 
Basically, I have 3 classes: directory class, a file class, and includefile class (that extends file)
 
The directory class has 1 arraylist to hold other directories and 1 array list to hold files and the file class has 1 arraylist to hold includefile's and 1 arraylist to hold strings.
 
I am having trouble getting the include file list to show up properly (directories and files are ok). I think it's because in the includefile class, I xmlinclude(gettype(file))
and in the file class, since i have a list of include files, i xmlinclude(gettype(includefile)) I think this circular definition may be causing the problem?
How should these xmlincludes be handled?
 
Thanks!
GeneralRe: help with serializationmemberLiong2 Apr '03 - 5:28 
A good question! If you can email (liong_ng@yahoo.com) me your code snippet, I can try to figure it out.
GeneralRe: help with serializationmemberbannistj18 Nov '03 - 4:20 
You can if it is a tree stucture, like a directory, but if the Formatter encounters a loop (.i.e see the same object twice) an exception is thrown to the effect.
To overcome this problem with serializing object meshes i you need to have your objects implement ISerializable and override the normal but you still lose the structure.

 
Jan
QuestionHow to serialize non primitive properties?memberleppie28 Jul '02 - 9:11 
Hi, nice article Smile | :)
 
I was working with this the other day and although i took a much longer route, i just couln't figure out how to serialize Font's Color's etc. to XML. I get the no default constructor exception.
 
Previously I was using the BinaryFormatter class to serialize fonts, but it doesnt seem to work XmlSerializer Frown | :(
 
Have you come accross this too?
 
MYrc : A .NET IRC client with C# Plugin Capabilities. See
http://sourceforge.net/projects/myrc
for more info. Big Grin | :-D
AnswerRe: How to serialize non primitive properties?membercschmidt30 Jul '02 - 7:03 
Hi,
 
I'm not the author of the article but in case you have not received an answer to you question, take a look at http://www.crownwood.net. This site offers an open source C# Docking/Menu/etc. control (MagicUI) which saves and restores settings to and from xml. Even if you don't use the tool, the source is very helpful.
 
Craig
GeneralRe: How to serialize non primitive properties?memberleppie30 Jul '02 - 12:19 
thx i've had a quick look , but i run into the same problem, without a default constructor you are stuck Frown | :(
 
i will look more tomorrow, way past bed time
 
MYrc : A .NET IRC client with C# Plugin Capabilities. See
http://sourceforge.net/projects/myrc
for more info. Big Grin | :-D
AnswerRe: How to serialize non primitive properties?memberLiong1 Aug '02 - 11:24 
Hi, Thanks.
 
Since Font and Color do not have a default constructor, it won't work with XmlSerializer. Unfortunately, we also cannot create a class that derives from Font or Color since they are sealed.
 
You may have to write your own Font or Color serializer class utilizing XmlTextWriter or similar classes.
 
I hope it works out for you.
 
Liong Ng
AnswerRe: How to serialize non primitive properties?memberomoshima9 Apr '03 - 11:54 
why don't you do something like:
 
public class YourClassName
{
	private Color c;
	
	public YourClassName(){}
	
	public YourClassName(Color c)
	{
		this.c = c;
	}
	
	public int MyFontColor
	{
		get{return this.c.ToArgb();}
		set{this.c = new Color.FromArgb(value);}
	}
}

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 27 Jul 2002
Article Copyright 2002 by Liong Ng
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid