Monday, May 10, 2010

Xml Serialization



10-May-2010
Here's a basic example of serialising (Yes that's right in this part of the world that's how its spelt), an object to Xml:
[Edit: BTW you will need to add a reference to System.Runtime.Serialization in addition to the standard C# console app references).


namespace XmlSerialisation {
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;
    using System.Xml;

    public class Program {
        public static void Main(string[] args) {
            var subject = new KeyValuePair<int, string>(21, "Full House Aces High");

            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder)) {
                var serialiser = new XmlSerializer(typeof(KeyValuePair<int, string>));
                builder.AppendLine();
                builder.AppendLine("XmlSerializer:");
                serialiser.Serialize(writer, subject);
                builder.AppendLine();
            }

            using (var writer = new StringWriter(builder)) {
                using (var xmlWriter = new XmlTextWriter(writer)) {
                    var wcfSerialiser = new System.Runtime.Serialization.DataContractSerializer(typeof(KeyValuePair<int, string>));
                    builder.AppendLine();
                    builder.AppendLine("WCF Serialisation:");
                    wcfSerialiser.WriteObject(xmlWriter, subject);
                    builder.AppendLine();
                }
            }

            Console.WriteLine(builder.ToString());
        }
    }
}

Here's the output of the program:

XmlSerializer:
<?xml version="1.0" encoding="utf-16"?>
<KeyValuePairOfInt32String xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

WCF Serialisation:
<KeyValuePairOfintstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xml
ns="http://schemas.datacontract.org/2004/07/System.Collections.Generic"><key>21<
/key><value>Full House Aces High</value></KeyValuePairOfintstring>


One other thing I was trying to prove with this code is the different behaviours of the two different serialisers. The standard XmlSerializer serialises based on public properties (and takes into account Xml attributes you may have decorated your members with, for example [System.Xml.Serialization.XmlElement("ReplacementMemberName")]).

The DataContractSerializer looks at fields for its serialisation process, and will ignore the System.Xml.Serialization attributes.

You also have a Json serialiser at your disposal too, see here for more info.

[Edit 28-June-2010]
Here's an example of Deserialisation:


    private static T SetUpSampleData<T>(string sampleDataFile) where T : class, new()
        {
            if (File.Exists(sampleDataFile))
            {
                // var serialiser = new System.Xml.Serialization.XmlSerializer(typeof(MainWindowController));
                var serialiser = new System.Runtime.Serialization.DataContractSerializer(typeof(MainWindowController));
                using (var stream = new FileStream(sampleDataFile, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = XmlReader.Create(stream))
                    {
                        // var deserialisedObject = serialiser.Deserialize(reader);  // XmlSerialiser
                        var deserialisedObject = serialiser.ReadObject(reader);      // WCF DataContract Serialiser
                        return deserialisedObject as T;
                    }
                }
            }

            return null;
        }

No comments:

Post a Comment