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

Tagged as

Serialize and deserialize generic arrays

, 28 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Code to serialize and deserialize generic arrays.

We often use things like Configuration[] configs and like to manage that in an XML file that we can edit. Two simple extension methods can help you here.

public static string SerializeArray(this T[] list)
    System.Xml.XmlDocument doc = new XmlDocument();
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(list.GetType());
    System.IO.MemoryStream stream = new System.IO.MemoryStream();
        serializer.Serialize(stream, list);
        stream.Position = 0;
        return doc.InnerXml;
    catch { throw; }
public static T[] DeSerializeArray(string serializedData)
    T[] list = null;
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T[]));
    XmlReader xReader = XmlReader.Create(new StringReader(serializedData));
        list = (T[])serializer.Deserialize(xReader);
    return list;

Code to serialize the data:

string xml1 = _environments.SerializeArray();
StreamWriter writer = new StreamWriter("config.xml");

To deserialize the data:

string xml = File.ReadAllText("config.xml");
_environments = Extensions.DeSerializeArray(xml);

If you don't like the root ArrayOfConfiguration, you can change the extension methods to use a XmlRootAttribute like:

XmlRootAttribute root = new XmlRootAttribute(rootName);
System.Xml.Serialization.XmlSerializer serializer = 
   ew System.Xml.Serialization.XmlSerializer(typeof(T[]), root);

You need to use the matching name in both methods to get it working.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

H. Tony
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

GeneralReason for my vote of 5 These kind of examples really helps ... PinmemberRobRoo2-Jan-12 20:58 
GeneralOk I sort of get it. Do you have to have a XML schema set u... Pinmemberverber0012-Jan-12 16:59 
GeneralRe: the problem I encountered was that some one created a List o... PinmemberH. Tony3-Jan-12 8:07 
GeneralForgive the noob question but what exactly does this code do... Pinmemberverber0012-Jan-12 16:48 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 28 Dec 2011
Article Copyright 2011 by H. Tony
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid