Click here to Skip to main content
Email Password   helpLost your password?

Demo form - Load-Save objects to XML

Contents

Introduction

This C# program demonstrates loading and saving an object containing a bitmap and collections to an XML file using .NET XML serialization. XML serialization enables an object's public fields and properties to be saved and loaded to/from an XML file.

This article focuses on the C# 2.0 (Visual Studio 2005) implementation. The C# 1.1 code does not use Generics and static class declaration, because those features are only available in C# 2.0.

Background

After discovering the usefulness of XML in storing data (including configuration settings for a program), I needed a solution to load and save an object's public fields and properties to/from an XML file without the complexity of navigating through the DOM (Document Object Model). I also wanted to provide an abstraction of the XML data as class objects, and only concern myself with the XML specifics when saving or loading data to/from a file. In addition, this 'load/save to XML' framework had to be reusable in other projects.

A practical solution - and the one demonstrated here - is to use the functionality provided by the .NET System.Xml.Serialization.XmlSerializer class encapsulated within a new class to provide loading and saving of an object to/from an XML file.

Using the code

File descriptions

Enabling XML serialization of an object

Before we can serialize an object to XML, the object's class code must include various custom metadata attributes (e.g., [XmlAttributeAttribute(DataType="date")]) to tell the compiler that the class and its field and/or properties can be serialized. For example, in the Customer class:

// Set this 'Customer' class as the root node

// of any XML file its serialized to.

[XmlRootAttribute("Customer", Namespace="", IsNullable=false)]
public class Customer
{
    private Bitmap picture;

    /// <summary>

    /// Default constructor for this class

    /// (required for serialization).

    /// </summary>

    public Customer()
    {
    }

    // Set this 'DateTimeValue' field

    // to be an attribute of the root node.

    [XmlAttributeAttribute(DataType="date")]
    public System.DateTime DateTimeValue;

    // By NOT specifing any custom

    // Metadata Attributes, fields will be created

    // as an element by default.

    public int CustomerID;
    public string CustomerName;
    public int Age;

    // Set serialization to IGNORE

    // this field (ie. not add it to the XML).

    [XmlIgnoreAttribute()]
    public bool CustomerPaid;

    // Set serialization to IGNORE this property

    // because the 'PictureByteArray' property

    // is used instead to serialize

    // the 'Picture' Bitmap as an array of bytes.

    [XmlIgnoreAttribute()]
    public Bitmap Picture
    {
        get { return picture; }
        set { picture = value; }
    }

    // Serializes the 'Picture' Bitmap to XML.

    [XmlElementAttribute("Picture")]
    public byte[] PictureByteArray
    {
        get 
        { 
            if (picture != null)
            {
                TypeConverter BitmapConverter = 
                     TypeDescriptor.GetConverter(picture.GetType());
                return (byte[]) 
                     BitmapConverter.ConvertTo(picture, typeof(byte[]));
            }
            else
                return null;
        }
        
        set 
        { 
            if (value != null)
                picture = new Bitmap(new MemoryStream(value)); 
            else
                picture = null; 
        }
    }

    // Serializes an ArrayList as a "Hobbies" array

    // of XML elements of type string named "Hobby".

    [XmlArray ("Hobbies"), XmlArrayItem("Hobby", typeof(string))]
    public System.Collections.ArrayList Hobbies = 
           new System.Collections.ArrayList();

    // Serializes an ArrayList as a "EmailAddresses" array

    // of XML elements of custom type EmailAddress named "EmailAddress".

    [XmlArray ("EmailAddresses"), 
     XmlArrayItem("EmailAddress", typeof(EmailAddress))]
    public System.Collections.ArrayList EmailAddresses = 
           new System.Collections.ArrayList();
}

Class to encapsulate XML serialization

The ObjectXMLSerializer class is used to encapsulate XML serialization, so that we can load and save an object regardless of its data type, with the help of Generics. Calling objects use the overloaded public methods, Load and Save.

The Load methods deserialize XML data from a previously serialized XML file into an object's public fields and properties.

The Save methods serialize an object's public fields and properties to an XML file.

Methods with the SerializedFormat parameter allow setting of the serialization format - either XML document format, or binary format. If no serialization format is specified, XML document formatting is used, by default.

The following private methods within ObjectXMLSerializer implement the core functionality for loading or saving data. Note that T is the placeholder for the generic type used to represent a serializable object:

private static T LoadFromBinaryFormat(string path, 
                 IsolatedStorageFile isolatedStorageFolder)
{
    T serializableObject = null;

    using (FileStream fileStream = 
           CreateFileStream(isolatedStorageFolder, path))
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        serializableObject = binaryFormatter.Deserialize(fileStream) as T;
    }

    return serializableObject;
}

private static T LoadFromDocumentFormat(System.Type[] extraTypes, 
        string path, IsolatedStorageFile isolatedStorageFolder)
{
    T serializableObject = null;

    using (TextReader textReader = 
           CreateTextReader(isolatedStorageFolder, path))
    {
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
        serializableObject = xmlSerializer.Deserialize(textReader) as T;

    }

    return serializableObject;
}

private static void SaveToBinaryFormat(T serializableObject, 
        string path, IsolatedStorageFile isolatedStorageFolder)
{
    using (FileStream fileStream = 
           CreateFileStream(isolatedStorageFolder, path))
    {
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(fileStream, serializableObject);
    }
}

private static void SaveToDocumentFormat(T serializableObject, 
        System.Type[] extraTypes, string path, 
        IsolatedStorageFile isolatedStorageFolder)
{
    using (TextWriter textWriter = 
           CreateTextWriter(isolatedStorageFolder, path))
    {
        XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
        xmlSerializer.Serialize(textWriter, serializableObject);
    }
}

private static FileStream CreateFileStream(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
{
    FileStream fileStream = null;

    if (isolatedStorageFolder == null)
        fileStream = new FileStream(path, FileMode.OpenOrCreate);
    else
        fileStream = new IsolatedStorageFileStream(path, 
                     FileMode.OpenOrCreate, isolatedStorageFolder);

    return fileStream;
}

private static TextReader CreateTextReader(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
{
    TextReader textReader = null;

    if (isolatedStorageFolder == null)
        textReader = new StreamReader(path);
    else
        textReader = new StreamReader(new IsolatedStorageFileStream(path, 
                                  FileMode.Open, isolatedStorageFolder));

    return textReader;
}

private static TextWriter CreateTextWriter(IsolatedStorageFile 
                            isolatedStorageFolder, string path)
{
    TextWriter textWriter = null;

    if (isolatedStorageFolder == null)
        textWriter = new StreamWriter(path);
    else
        textWriter = new StreamWriter(new IsolatedStorageFileStream(path, 
                          FileMode.OpenOrCreate, isolatedStorageFolder));

    return textWriter;
}

private static XmlSerializer CreateXmlSerializer(System.Type[] extraTypes)
{
    Type ObjectType = typeof(T);

    XmlSerializer xmlSerializer = null;

    if (extraTypes != null)
        xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
    else
        xmlSerializer = new XmlSerializer(ObjectType);

    return xmlSerializer;
}

Saving an object to an XML file

The following example code shows how to use the ObjectXMLSerializer class to save a Customer object to an XML file (in document format). We first build a Customer object from the values in the user interface, by calling our custom BuildCustomerFromForm method:

// Create customer object based on Form values.

Customer customer = this.CreateCustomer();

//Save customer object to XML file using our ObjectXMLSerializer class...

ObjectXMLSerializer<Customer>.Save(customer, XML_FILE_NAME);

Loading an object from an XML file

The following example code shows how to use the ObjectXMLSerializer class to load a Customer object from an XML file (in document format):

// Load the customer object from the XML file using our custom class...

customer = ObjectXMLSerializer<Customer>.Load(XML_FILE_NAME);

Points of interest

Storing a bitmap in an XML file

The Customer class includes a Picture property that stores a Bitmap object. Because a Bitmap cannot be automatically serialized/deserialized using the .NET System.Xml.Serialization.XmlSerializer class, the Bitmap object is saved to the XML file as an array of bytes, and converted back into a bitmap when the XML file is loaded.

Conversion from a Bitmap object to a byte array is achieved using the Bitmap object's System.ComponentModel.TypeConverter. Conversion from a byte array back to a Bitmap object is achieved using a System.IO.MemoryStream object supplied to the Bitmap object's constructor.

Note that two public properties are used to enable storing of the Bitmap: Picture and PictureByteArray. The Picture property is ignored during serialization (by using the XmlIgnoreAttribute attribute) because it's of type Bitmap. The value the Picture property gets or sets is stored in XML, during serialization, using the PictureByteArray property which performs the 'Bitmap to byte array' conversion (and vice-versa).

Storing a collection of strings in an XML file

The Customer class includes a Hobbies field that stores an ArrayList collection of strings. The attributes for the Hobbies field are as follows:

[XmlArray ("Hobbies"), XmlArrayItem("Hobby", typeof(string))]

The XML attribute, XmlArray, specifies the serialization of the Hobbies field as an array of XML elements named "Hobbies". The XML attribute, XmlArrayItem, defines the name of the array item as it will be stored in the XML file, as "Hobby", and its storage type as string. The following example shows how the array of Hobbies XML elements might appear in an XML file:

<Hobbies>
  <Hobby>Golf</Hobby>

  <Hobby>Tennis</Hobby>
  <Hobby>Reading</Hobby>
</Hobbies>

Storing a collection of custom objects in an XML file

The Customer class includes an EmailAddresses field that stores an ArrayList collection of custom EmailAddress objects. The attributes for the EmailAddresses field are defined similar to the Hobbies field.

Immediately before the class declaration, the XML attribute Serializable specifies that the EmailAddress class is serializable.

A default constructor with no parameters is included in the EmailAddress class as it is required for the .NET serialization.

The XML attribute XmlAttribute is specified for both fields of the EmailAddress class to demonstrate the usage of XML attributes. The following example shows how the array of EmailAddresses XML elements - with its fields stored as XML attributes - might appear in an XML file:

<EmailAddresses>

  <EmailAddress Address="joebloggs@zenicom.com" Destination="Business" />
  <EmailAddress Address="joebloggs@athome.com" Destination="Home" />
  <EmailAddress Address="joebloggs@hotmail.com" Destination="Other" />
</EmailAddresses>

References

History

Version 1.0

Original submission.

Version 2.0

Version 2.1

Version 3.0

Version 3.1

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalspecial characters
oliver.hawk
3:54 20 May '09  
Hi,

great example. I've tried it with special german characters.
But when I put an ü into the xml, I'll get an � returned.

I've looked into the code and tried to create the textreader with a special encoding.
private static TextReader CreateTextReader(IsolatedStorageFile isolatedStorageFolder, string path)
--> textReader = new StreamReader(new IsolatedStorageFileStream(path, FileMode.Open, isolatedStorageFolder), System.Text.Encoding.GetEncoding("utf-8"));
or textReader = new StreamReader(new IsolatedStorageFileStream(path, FileMode.Open, isolatedStorageFolder), System.Text.Encoding.GetEncoding("iso-8859-1"));

but this was of no help.

have you any idea where this could be changed?

regards
Oliver
GeneralSerialization question.
irina-z
7:33 20 Apr '09  
I am wondering, if there is a way to create a movie class that produces XML as following:


<arrayofmovie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
   <movie movierating="6.9">
      Starship Troopers
   </movie>
   <movie movierating="5.4">
      Ace Ventura: When Nature Calls
   </movie>
</arrayofmovie>

public class Movie
{
   // -?-   [XmlElement("MovieName")]
   public string Title
   { get; set; }

   [XmlAttribute("MovieRating")]
   public float Rating
   { get; set; }
}
GeneralGreat Example / VB
marchesb
6:47 4 Sep '08  
This is a very helpful example. Thanks for posting it! Smile I converted the image serialization pieces of it to VB for a legacy project I had and it worked great.
Generalserialization to App.config
PetoG
23:22 3 Sep '08  
Is it possible to serialize list's elements to App.config?
GeneralBe careful with FileMode.OpenOrCreate..
st14
16:56 13 Aug '08  
Great project. I,ve found it very good. One problem today I must report.

When using Isolated Storage the current code uses FileMode.OpenOrCreate. If your serialised XML data has reduced in size the old data will remain at the end of the file. You then get the message : "Data at the root level is invalid" This only happens with IS in this project. Solution is to use FileMode.Create instead.

Thanks
QuestionWhy Static ?
vertex85
1:10 20 May '08  
Hi,

Your class is very fine. I use it a lot to quicky load save XML, but I just got into a performance issue.

Wanting to load many files of the same type, (foreach [...] ObjectXmlSerializer.Load(...) ), it's very slow, due to the fact that each time you create a serializer, an assembly is built on the fly.

Have you a non-static version or this loader, or do you see the mean to have a kind of cache ?
If not, I'll have to spend a little time to find a workaround...

Regards

AnswerRe: Why Static ?
T-C
2:21 20 May '08  
Unfortunately I do not have a non-static version of this class.

My understanding is that the JIT compiler keeps track of type-specific code it has already generated so repeated calling of a static method with the same generic parameters/return types should not incur a performance overhead. Are you sure the generic implementation is the cause of the slow performance?

Aside from writing custom type specific code, perhaps adding overloaded Load and Save methods to handle multiple files/objects will improve performance?

For example:
public static List<T> Load(string[] paths)
public static void Save(Dictionary<string, T> SerializableObjectsWithPath)

The generic Dictionary parameter would contain as its key the path of the file and its value as the serializable object to be saved to the path.

You could copy existing code in the ObjectXMLSerializer class for the Load and Save methods and adjust for multiple objects accordingly.

Hope this helps!

Smile

Born to code.

GeneralRe: Why Static ?
vertex85
3:20 20 May '08  
Thank you for your very quick answer.

I don't know the performance issue comes from the generic stuff. It's only the XmlSerializer multiple creations which are slow.

I've just tried your solution of a "multiple loading" overload, and with only one XmlSerializer created on the fly(see it in output window), all is now very fast.
That will do the trick for the moment. If I find time, I'll try to make the class static or not, if it helps...

Thank you.

Regards


------------

For information :

public static List<T> Load(string[] paths, System.Type[] extraTypes)
{
return LoadFromDocumentFormat(extraTypes, paths, null);
}

private static List<T> LoadFromDocumentFormat(System.Type[] extraTypes, string[] paths, IsolatedStorageFile isolatedStorageFolder)
{
XmlSerializer xmlSerializer = CreateXmlSerializer(extraTypes);
List<T> list = new List<T>();
foreach (string path in paths)
{
using (TextReader textReader = CreateTextReader(isolatedStorageFolder, path))
{
list.Add(xmlSerializer.Deserialize(textReader) as T);
}
}
return list;
}

QuestionVSTS - "The Web Server for page http://localhost/abc/abc.aspx" did not respond. Check that the web server is running and visible on the network".
kanilkumar
16:43 19 May '08  
I am working with VSTS Unit testing for my web application whichis built in VS.net 2005. When I run my Unit Test Case from VSTS, its running fine some times and suddenly its giving error "The Web Server for page http://localhost/abc/abc.aspx" did not respond. Check that the web server is running and visible on the network". But my web application running perfectly. Only i am getting this problem when i run my unit test.



Please help us to solve this issue, if any one know the solution.



Thanks in Advance

Anil
QuestionNot knowing the object type...
Mogyi
1:36 26 Sep '07  
Hi everyone!

I have a problem... I have to load xml files without knowing the object types saved in these Sniff
Any suggestion how to achieve this ?


Questionvery well, but doesn't work with xml ENTITY
Stoyan K Petrov
9:50 18 Sep '07  
I see that the ObjectXMLSerializer class doesn't work with xml ENTITY.
for example:

<!DOCTYPE Customer [<!ENTITY pref "123">]>

xmlns:xsd="http://www.w3.org/2001/XMLSchema" DateTimeValue="2007-09-18">
12
Joe Bloggs - &pref;
28
....
What you think is it possible to work with entities?
QuestionA list of lists
halokitty82
12:43 17 Sep '07  
I'm new and I'm afraid I'm still a little confused about serialization after this article. Is there a way to serialize the following without adding an extra level of tags to encapsulate the Roles? Currently, I created a Root class and a Group class. The Root class creates an ArrayList Groups, containing Group objects. However, I'm having trouble in the Group class, because the number of Role tags per Group varies.

<Root>
  <Groups>
    <Group attribute="">
      <Role></Role>
      <Role></Role>
    </Group>
    <Group attribute="">
      <Role></Role>
      <Role></Role>
      <Role></Role>
      <Role></Role>
    </Group>
  </Groups>
</Root>

Any advice would be appreciated. Thanks.
GeneralRe: A list of lists
pH++
7:21 4 Jan '08  
You try to create an object derived from IXmlSerializable.

Example:

public class ArraySerializable: IXmlSerializable
{
public string attribute;

public List items;

...

public void ReadXml(XmlReader xr)
{
xr.Read(); // move past container

while (xr.NodeType != XmlNodeType.EndElement)
{
if (xr.Name == "Items")
{
string attribute = xr.GetAttribute("AttributeItems");
}

if (xr.Name == "Item")
{
string value = xr.GetAttribute("AttributeItem");
}

xr.Read();
}
}

public void WriteXml(XmlWriter xw)
{
xw.WriteStartElement("Items");
xw.WriteAttributeString("AttributeItems", attribute);

foreach (ArrayItem item in items)
{
xw.WriteStartElement("Item");
xw.WriteAttributeString("AttributeItem", item.ToString());
xw.WriteEndElement();
}
xw.WriteEndElement();
}

public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
}

GeneralXML Object Serialization
getnanda@gmail.com
2:06 16 Aug '07  
I am using XML Object Serialization to save data.
//Sample XML


<?xml version="1.0" encoding="utf-8"?>
<ParameterList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Parameters>
      <Parameter>


/////////////////////////////////////////////////////////////////////////////

My class name is "ParameterList". Is there any way not to display the attributes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

Thanks in advance
Nanda
GeneralRe: XML Object Serialization
pH++
7:23 4 Jan '08  
You try to refer the following link:
http://www.csharper.net/blog/serializing_without_the_namespace__xmlns__xmlns_xsd__xmlns_xsi_.aspx[^]
GeneralNice class interface!
derekliang
8:23 8 Aug '07  
I think this should be included in your standard class library.

Good job!
Questionarray question
Nazz2
3:01 14 Jun '07  
Should be possible the array serialization without the EmailAddresses tag:

EmailAddress Address="joebloggs@zenicom.com" Destination="Business"
EmailAddress Address="joebloggs@athome.com" Destination="Home"
EmailAddress Address="joebloggs@hotmail.com" Destination="Other"

instead of:

EmailAddresses
EmailAddress Address="joebloggs@zenicom.com" Destination="Business"
EmailAddress Address="joebloggs@athome.com" Destination="Home"
EmailAddress Address="joebloggs@hotmail.com" Destination="Other"
/EmailAddresses

Thanks and good job
QuestionWhy no Try/Catch block?
PaulBHermans
5:11 19 Apr '07  
First, your article really helped me a ton. Thanks

Second, When I tried to use it on some classes I had defined, it blew up. It turned out that the problem was that I had accidentally declared a class as private instead of public, so when we got to the CreateXmlSerializer(..) method it failed....and allowed the error to bubble up to me.

My question is, why did you choose not to put Try/Catch blocks around the code so that it looked as follows?
private static XmlSerializer CreateXmlSerializer(System.Type[] extraTypes)
{
Type ObjectType = typeof(T);

XmlSerializer xmlSerializer = null;
try
{
if (extraTypes != null)
xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
else
xmlSerializer = new XmlSerializer(ObjectType);
}
catch (Exception e)
{
return null;
}

return xmlSerializer;
}

Thanks in advance.

Paul Hermans
www.BenemTech.com

AnswerRe: Why no Try/Catch block?
S.B.
14:05 14 Apr '08  
Because that defeats the whole purpose of exceptions. What you suggest would simply hide the exception so you'd never know why you can't create an XmlSerializer. You'd just get a null reference mysteriously returned and no more information unless you poked around with the debugger.

The fact that an exception was raised means that you have done something seriously wrong and the class by itself can't recover from it. The only thing it can do is raise an exception and propagate it out to calling code in the hope that it can handle it.
Question&quot;error reflecting type&quot; [modified]
Masked Dave
5:05 6 Apr '07  
I'm given this error message when trying to serialize with your ObjectXMLSerializer:

System.InvalidOperationException was caught
Message="There was an error reflecting type 'Class_Library.Game'."
Source="System.Xml"
StackTrace:
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel)
at System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModel model, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at Class_Library.ObjectXMLSerializer`1.CreateXmlSerializer(Type[] extraTypes) in J:\My Documents\Visual Studio 2005\Projects\Third Year Project\Class Library\ObjectXMLSerializer.cs:line 374
at Class_Library.ObjectXMLSerializer`1.SaveToDocumentFormat(T serializableObject, Type[] extraTypes, String path, IsolatedStorageFile isolatedStorageFolder) in J:\My Documents\Visual Studio 2005\Projects\Third Year Project\Class Library\ObjectXMLSerializer.cs:line 383
at Class_Library.ObjectXMLSerializer`1.Save(T serializableObject, String path) in J:\My Documents\Visual Studio 2005\Projects\Third Year Project\Class Library\ObjectXMLSerializer.cs:line 183
at Designer.FrmMain.SaveGame() in J:\My Documents\Visual Studio 2005\Projects\Third Year Project\Designer\FrmMain.cs:line 195


The error is being thrown here, when the XmlSerializer is initialised without 'extratypes'
private static XmlSerializer CreateXmlSerializer(System.Type[] extraTypes)
{
Type ObjectType = typeof(T);

XmlSerializer xmlSerializer = null;

if (extraTypes != null)
xmlSerializer = new XmlSerializer(ObjectType, extraTypes);
else
xmlSerializer = new XmlSerializer(ObjectType);

return xmlSerializer;
}


This is the top of the class in question
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Xml.Serialization;

namespace Class_Library
{
[XmlRootAttribute("Game", Namespace = "", IsNullable = false)]
public class Game
{
private string _title;
private string _designer;
private ResolutionStruct _resolution;
private List< string > _inventoryInUse;
private Dictionary< string, Room > _rooms;
private Dictionary< string, VisibleItem > _visibleItems;
private List< string > _playerCharacters;

public Game()
{
Title = "";
Designer = "";
Resolution = new ResolutionStruct(1024, 768);
InventoryInUse = new List< string >();
Rooms = new Dictionary< string, Room >();
VisibleItems = new Dictionary< string, VisibleItem >();
PlayerCharacters = new List< string >();
}


Any advise you could give would be greatly appreciated, thanks.

Note, the Dictionary properties in the class have [XmlIgnore] tags over them and a second property reads/writes their contents to a List of that type.


-- modified at 10:53 Friday 6th April, 2007
QuestionSerialise to string or memory stream
mikestringfellow
17:44 23 Jan '07  
Excellent tool - thanks! Smile

How would I use/extend this to output to memory rather than a file?

Thanks.

MikeS
GeneralXmlInclude and ExtraTypes
mikestringfellow
23:14 16 Jan '07  
Confused
I'm serializing a collection of base objects fine. But when I include a subtype into the array the serialize thows an erorr telling me to use XmlInclude(Type)custom attrib. I've done this, and also tried adding it into the 'extra type array' but still get the exception.

How do I get a collection of base types to correctly serialize both the base and derived types it contains? I can work around this, but it dirties my class model...

Thanks, MikeS.
GeneralRe: XmlInclude and ExtraTypes
mikestringfellow
15:02 17 Jan '07  
Scratch that - I changed to an array list which works fine. D'Oh!



Cheers, MikeS
Generalcan't add collection of objects....
mikilior
6:30 1 Jan '07  
hi ,
i am trying to add collection of objects named "XmlFile".
anyway any object i add delets the previous one and i can only add one object.
see config.xml:

<xmlFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
2007-01-01T17:53:05.8777237+02:00
<xmlFileID>0</xmlFileID>
<xmlFileName>QA_WORK_PLAN12_Odddct218.xml</xmlFileName>
<xmlFilePath>C:\Documents and Settings\mikili\Desktop\QA_WORK_PLAN12_Odddct.mpp</xmlFilePath>
QA_WORK_PLAN12_Odddct.mpp

</xmlFile>

please help!!!!
GeneralCompression [modified]
Mivano
23:46 6 Nov '06  
I added compression using GZIP to the ObjectXMLSerializer.cs class. If you select DocumentCompressed, a GZIPStream is used to save or load the file. After compression/decompression, the normal xml serialization is executed. You can find the file at http://composestar.svn.sourceforge.net/viewvc/composestar/trunk/StarLight/Source/Repository/ObjectXMLSerializer.cs?view=markup
[^]

-- modified at 4:51 Tuesday 7th November, 2006


Last Updated 1 Sep 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010