If you want to serialize an object to a string or want to deserialize a string back to an object, you can use the following class:

 

The XmlSerializationTask class

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

namespace Rvl.NewCode.Test.Task
{
    /// <summary>
    /// This class is used for serializing a object to string and back.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class XmlSerializationTask<T> where T : class, new()
    {
        /// <summary>
        /// Use this property for types that are unkown at compiletime.
        /// </summary>
        public Type[] ExtraTypes { get; set; }
        /// <summary>
        /// Serializes the object to string.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public string SerializeObjectToString(T source)
        {
            StringBuilder result = new StringBuilder(string.Empty);
            using (StringWriter writer = new StringWriter(result))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T), ExtraTypes);
                xs.Serialize(writer, source);
            }
            return result.ToString();
        }
        /// <summary>
        /// Deserializes from string.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        public T DeserializeFromString(string source)
        {
            T result;
            using (StringReader reader = new StringReader(source))
            {
                XmlSerializer xs = new XmlSerializer(typeof(T), ExtraTypes);
                result = xs.Deserialize(reader) as T;
            }
            return result;
        }
    }
}

 

Using the XmlSerializationTask class

public void TestXmlSerializationTask()
{
    // DynamicTask, is just a class I created with 3 properties:
    var dynamicTask = new DynamicTask 
    { 
        Id = Guid.NewGuid(), 
        AssemlbyPath= Environment.NewLine, 
        TypeDescription="Test" 
    };
    var serializeTask = new XmlSerializationTask<DynamicTask>();
    string serializedObject = serializeTask.SerializeObjectToString(dynamicTask);
    DynamicTask newDynamicTask = serializeTask.DeserializeFromString(serializedObject);
}

Produced XML

<?xml version="1.0" encoding="utf-16"?>

<DynamicTask xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Id>5b1c6ca4-a8a3-46fc-8496-8caa8c37a47f</Id>

  <AssemlbyPath>C:\Temp\Test.dll</AssemlbyPath>

  <TypeDescription>Test</TypeDescription>

</DynamicTask>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.