HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Generic methods for serializing and deserialzing xml files using streams

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
genericserializingdeserialzingxmlmethodsfilesforusingstreamsand

Problem

using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Common.Extensions
{
    /// 
    /// Contains the logic for streaming extensions.
    /// 
    public static class StreamExtensions
    {
        /// 
        /// Serialize an object.
        /// 
        /// The type of the object that gets serialized.
        /// The stream to which the bytes will be written.
        /// The object that gets serialized.
        public static void SerializeObject(this Stream stream, T serializableObject) where T : IXmlSerializable
        {
            var writerSettings = new XmlWriterSettings();

            writerSettings.Indent = true;
            writerSettings.IndentChars = "    "; // 4 spaces
            writerSettings.Encoding = Encoding.UTF8;

            using (var xmlWriter = XmlWriter.Create(stream, writerSettings))
            {
                serializableObject.WriteXml(xmlWriter);
            }

            stream.Close();
        }

        /// 
        /// Deserialize a stream and return the object.
        /// 
        /// The type of the object that returns from the deserialization.
        /// The stream which contains the bytes to deserialize.
        /// The object recovered.
        public static T DeserializeObject(this Stream stream) where T : IXmlSerializable
        {
            using (var xmlTextReader = XmlReader.Create(stream))
            {
                var serializer = new XmlSerializer(typeof(T));
                T result = (T)serializer.Deserialize(xmlTextReader);
                stream.Close();
                return result;
            }
        }
    }
}


I have made a class which can serialize a generic object which implements the interface IXmlSerializable and can deserialize an xml file to that same object. The idea behind this is as follows: we are using a lot of xml files to (for example) write configurations to. Since the configuration classes are often different we needed a gene

Solution

writerSettings.IndentChars = "    "; // 4 spaces


by using

writerSettings.IndentChars = string.Empty.PadRight(4, ' ');


you wouldn't need that noisy comment.

One wouldn't expect that a passed in Stream get closed inside that method. The closing of a Stream should only belong to the creator of that stream.

In extension methods you should always check the argument which is reffered by this if it is null.

This is because that method can also be called like so

StreamExtensions.SerializeObject(null, someObject);


By checking (stream == null) and throwing an ArgumentNullException no unnecessary objects like XmlWriterSettings will be created.

Otherwise than the mentioned points your code looks clean and is easy to read.

Code Snippets

writerSettings.IndentChars = "    "; // 4 spaces
writerSettings.IndentChars = string.Empty.PadRight(4, ' ');
StreamExtensions.SerializeObject<someType>(null, someObject);

Context

StackExchange Code Review Q#109778, answer score: 4

Revisions (0)

No revisions yet.