Code Reference A collection of code for my reference (and perhaps other people too)

8Mar/100

More on Object Serialization to XML

It seems there are hundreds of ways to serialize object.

Here are just a few:

This one now seems very clumbsy. You pass in the object and the object type. It returns a string. I can't see the point of using this one any more now that I have found the next one.

public static string ContractObjectToXml<T>(T obj)
{
    DataContractSerializer dataContractSerializer = new DataContractSerializer(obj.GetType());
    String text;
    using (MemoryStream memoryStream = new MemoryStream())
    {
        dataContractSerializer.WriteObject(memoryStream, obj);
        byte[] data = new byte[memoryStream.Length];
        Array.Copy(memoryStream.GetBuffer(), data, data.Length);
        text = Encoding.UTF8.GetString(data);
    }
    return text;
}

This one I have started using is the most simple I have seen so far.

.
.
.
XElement xml = Microsoft.ServiceModel.Web.SerializationExtensions.ToXml(object);
.

This one returns a stream. It gives you a bit more control over what is shown and included in the XML.

public static Stream Serialize(Object obj)
{
            MemoryStream memoryStream = new MemoryStream();
            DataContractSerializer dcSerializer = new DataContractSerializer(obj.GetType());
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Encoding = new UTF8Encoding(false);
            xmlWriterSettings.ConformanceLevel = ConformanceLevel.Document;
            xmlWriterSettings.Indent = true;
            //xmlWriterSettings.OmitXmlDeclaration = true;

            using (XmlWriter xWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
            {
                dcSerializer.WriteObject(xWriter, obj);
                xWriter.Flush();
                //return Encoding.UTF8.GetString(memoryStream.ToArray());
                memoryStream.Position = 0;
                return memoryStream;
            }
}