Customize your .NET object XML serialization with .NET XML attributes

27 ביולי 2008

Hi,


Serialize .net object to XML is very simple operation but let's say you want to control on the serialization and decide on the name of the XML attributes and elements that .net serialization create for your object. Well this is very simple to achive using built-in XML attributes (attributes like: XmlType, XmlAttribute, XmlArray, XmlArrayItem and more…) .NET gives us.


The code example include 3 classes: MainStory, Story and BaseStory. MainStory and Story both inherits from BaseStory, MainStory also contain list (List<Story>) of stories objects.


BaseStory:



[Serializable]


public class BaseStory


{


    protected const string DescriptionContentDelimiter = ":::";


 


    [XmlAttribute("content")]


    public string Content { get; set; }


 


    [XmlAttribute("description")]


    public string Description { get; set; }


}


 


MainStory:


 



[Serializable]


[XmlType("mainStory", Namespace = "www.mycompany.com", TypeName = "MainStory")]


public class MainStory : BaseStory


{


    private List<Story> stories = new List<Story>();


 


    public MainStory()


    {


    }


 


    public MainStory(string content)


    {


        string[] data = Regex.Split(content, DescriptionContentDelimiter);


        Content = data[0];


 


        if (data.Length > 1)


        {


            Description = data[1];


        }


    }


 


    [XmlArray("stories")]


    [XmlArrayItem("story")]


    public List<Story> Stories


    {


        get { return stories; }


        set { stories = value; }


    }


}


 


Story:


 



[Serializable]


[XmlType("story")]


public class Story : BaseStory


{


    public Story()


    {


    }


 


    public Story(string content)


    {


        string[] data = Regex.Split(content, DescriptionContentDelimiter);


        Content = data[0];


 


        if (data.Length > 1)


        {


            Description = data[1];


        }


    }


}


 


You can see that I use the built-in .NET XML attributes in order to achive my goal and control the way my XML serialization will look.


You can check the result using simple XmlHelper class that serialize your .NET object to XML file:


 



public static class XmlHelper


{


    /// <summary>


    /// Serialize object in XML format inside a file.


    /// </summary>


    /// <param name="filename">The file that serialize object will be saved.</param>


    /// <param name="objectToSerialize">The object to serialize.</param>


    public static void SerializeObject(string filename,


              object objectToSerialize)


    {


        using (Stream stream = File.Open(filename, FileMode.Create, FileAccess.ReadWrite))


        {


            XmlSerializer xs = new XmlSerializer(objectToSerialize.GetType());


            XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);


            xs.Serialize(xmlTextWriter, objectToSerialize);


        }


    }


 


    /// <summary>


    /// Deserializes Object from a file.


    /// </summary>


    /// <typeparam name="T"></typeparam>


    /// <param name="filename">The file with the serialize object.</param>


    /// <returns></returns>


    public static T DeserializeObject<T>(string filename)


    {


        XmlSerializer xs = new XmlSerializer(typeof(T));


        T objectToSerialize;


 


        // Open for read only.


        using (Stream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))


        {


            objectToSerialize = (T)xs.Deserialize(stream);


        }


        return objectToSerialize;


    }


}


 

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*