Using XML Serialization with C# and SQL Server

Introduction

Serialization is the process of converting an object into a stream of bytes so that the object can be stored to memory, a database or a file. Its main purpose is to save the state of an object in order to be able to recreate it as needed. [MSDN].

The reverse process is called deserialization.

Whereas serialization is mostly known for data transmission, usually to web services, there are situations where serialized objects needs to be passed to SQL Server to be processed and saved.

In this article, 2 scenarios where XML Serialization can be used together with SQL Server shall be demonstrated.

XML Serialization

XML serialization serializes the public fields and properties of an object, or the parameters and return values of methods, into an XML stream that conforms to a specific XML Schema Definition Language (XSD) document. [MSDN].

Serialization

The first step is to define a custom class decorated with the Serializable attribute.

  1. [Serializable]  
  2. public class person  
  3. {  
  4.     public string name { getset; }  
  5.     public string surname { getset; }  
  6.     public string country { getset; }  
  7. }  
Next is a generic method that serializes an object to a XML string.

The method takes an object of type <T> and returns a serialized XML string.
  1. public static String ObjectToXMLGeneric<T>(T filter)  
  2. {  
  3.    
  4.     string xml = null;  
  5.     using (StringWriter sw = new StringWriter())  
  6.     {  
  7.    
  8.         XmlSerializer xs = new XmlSerializer(typeof(T));  
  9.         xs.Serialize(sw, filter);  
  10.         try  
  11.         {  
  12.             xml = sw.ToString();  
  13.    
  14.         }  
  15.         catch (Exception e)  
  16.         {  
  17.             throw e;  
  18.         }  
  19.     }  
  20.     return xml;  
  21. }  
  22.    
  23.     person p = new person();  
  24.     p.name = "Chervine";  
  25.     p.surname = "Bhiwoo";  
  26.     p.country = "Mauritius";  
  27.    
  28.     var xmlperson = Utils.ObjectToXMLGeneric<person>(p);  
Moreover, complex types can also be serialized as shown below:
  1. person p = new person { name = "Chervine"surname = "Bhiwoo"country = "Mauritius" };  
  2. person p1 = new person { name = "a"surname = "a"country = "Mauritius" };  
  3.    
  4. List<person> persons = new List<person>();  
  5. persons.Add(p);  
  6. persons.Add(p1);  
  7.    
  8. var xmlperson = Utils.ObjectToXMLGeneric<List<person>>(persons);  
The preceding operation will return an XML as in the following:
  1. <?xml version="1.0" encoding="utf-16"?>  
  2. <ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance   " xmlns:xsd="http://www.w3.org/2001/XMLSchema  ">  
  3.   <person>  
  4.     <name>Chervine</name>  
  5.     <surname>Bhiwoo</surname>  
  6.     <country>Mauritius</country>  
  7.   </person>  
  8.   <person>  
  9.     <name>a</name>  
  10.     <surname>a</surname>  
  11.     <country>Mauritius</country>  
  12.   </person>  
  13. </ArrayOfPerson>  
Deserialization

Just like for Serialization, the following is a generic method that takes an XML string as parameter and returns its corresponding object.
  1. public static T XMLToObject<T>(string xml)  
  2. {  
  3.   
  4.     var serializer = new XmlSerializer(typeof(T));  
  5.   
  6.     using (var textReader = new StringReader(xml))  
  7.     {  
  8.         using (var xmlReader = XmlReader.Create(textReader))  
  9.         {  
  10.             return (T)serializer.Deserialize(xmlReader);  
  11.         }  
  12.     }  
  13. }  
  14.    
  15. persons = Utils.XMLToObject < List<person>>(xmlperson);  
code

Scenario 1: Saving serialized XML as an XML Object in SQL Server

In this scenario, the user could create a custom filter based on several parameters. Please find some background about the problem below.

The requirements was to allow the user to save the custom filters, so that he just selects the filter from a list to filter information throughout the application.

Applying the filter was easily done using LINQ. The challenge was to save the filter since each user could save multiple filters, each having several conditions.

To save the filter, one of the solutions was to serialize the filter object and save it directly into the database. When needed, the filter is extracted from the database, deserialized and applied using LINQ.

The example below is a fictitious representation of the actual problem encountered.

The goal is to serialize an object to XML and save it in the database.

Defining the table and Stored Procedure

In the table below, the serialized XML will be stored in the column "filters" that is of type "XML".
  1. CREATE TABLE [dbo].[tbl_filters](  
  2.     [FilterId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [UserID] [varchar](20) NULL,  
  4.     [FilterDescription] [varchar](50) NULL,  
  5.     [Filters] [xml] NULL,  
  6. PRIMARY KEY CLUSTERED  
  7. (  
  8.     [FilterId] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS =ON)  
  10. )  
  11.    
  12. GO  
A Stored Procedure has been used to do the insert. Here also, the parameter "filters" is of type "XML".
  1. CREATE  PROCEDURE [dbo].[add_filter]  
  2.     -- Add the parameters for the stored procedure here  
  3. @user_id varchar(20),  
  4. @filter_description varchar(50),  
  5. @filters XML  
  6.    
  7. AS  
  8. BEGIN  
  9.     -- SET NOCOUNT ON added to prevent extra result sets from  
  10.     -- interfering with SELECT statements.  
  11.     SET NOCOUNT ON;  
  12. INSERT INTO [dbo].[tbl_filters]  
  13.            (  
  14.            [UserID]  
  15.            ,[FilterDescription]    
  16.            ,[Filters]  
  17.            )  
  18.      VALUES  
  19.           (@user_id,@filter_description ,@filters);  
  20.    
  21. END  
  22. GO  
The CustomFilter class has some descriptions about a filter and also several filters that could be applied in the application.
  1. [Serializable]  
  2. public class CustomFilter  
  3. {  
  4.     public int FilterID { getset; }  
  5.     public string UserID { getset; }  
  6.     public string Description { getset; }  
  7.    
  8.     public List<String> Type { getset; }  
  9.     public List<String> Category { getset; }  
  10.     public List<String> Region { getset; }  
  11.     public List<String> Branch { getset; }  
  12.    
  13.    
  14.     public override bool Equals(object obj)  
  15.     {  
  16.         if (obj == null)  
  17.             return false;  
  18.         var t = obj as CustomFilter;  
  19.         if (t == null)  
  20.             return false;  
  21.         if (FilterID == t.FilterID)  
  22.             return true;  
  23.         return false;  
  24.     }  
  25.    
  26.     public override int GetHashCode()  
  27.     {  
  28.         int hash = 13;  
  29.         hash += (hash * 31) + FilterID.GetHashCode();  
  30.    
  31.         return hash;  
  32.     }       
  33. }  
Create a method to pass XML parameters to the Stored Procedure

To pass XML parameters using SqlCommand, the parameter should be of type "SqlDbType.Xml".

The CreateFilter method serializes the object and passes it to the Stored Procedure.
  1. public void CreateFilter(CustomFilter filter)  
  2. {  
  3.     var FilterXML = Utils.ObjectToXMLGeneric<CustomFilter>(filter);  
  4.    
  5.     DBUtil db = new DBUtil();  
  6.    
  7.     SqlCommand cmd = new SqlCommand("add_filter");  
  8.     cmd.Parameters.Add("@user_id", SqlDbType.VarChar).Value = filter.UserID;  
  9.     cmd.Parameters.Add("@filter_description", SqlDbType.VarChar).Value = filter.Description;  
  10.     cmd.Parameters.Add("@filters", SqlDbType.Xml).Value = FilterXML;  
  11.    
  12.     db.DBConnect();  
  13.    
  14.     var result = db.XmlInsertUpdate(cmd);  
  15.    
  16.     db.DBDisconnect();  
  17. }  
The XmlInsertUpdate method takes the SqlCommand and executes the Stored Procedure.
  1. public Boolean XmlInsertUpdate(SqlCommand cmd)  
  2. {  
  3.     try  
  4.     {  
  5.         using (SqlConnection con = SQlConn)  
  6.         {  
  7.    
  8.             cmd.Connection = con;  
  9.             cmd.CommandType = CommandType.StoredProcedure;  
  10.             cmd.ExecuteNonQuery();  
  11.         }  
  12.     }  
  13.     catch (Exception e)  
  14.     {  
  15.         throw e;  
  16.     }  
  17.     return true;  
  18. }  
Create a filter

The codes below creates a new CustomFilter object and pass it to the CreateFilter method discussed previously.
  1. CustomFilter f1 = new CustomFilter();  
  2.    
  3. f1.UserID = "Chervine";  
  4. f1.Description = " Testing ";  
  5. f1.Branch = new List<string> { "Rose Belle""Mahebourg" };  
  6. f1.Category = new List<string> { "Small""Medium" };  
  7. f1.Region = new List<string> { "South" };  
  8. f1.Type = new List<string> { "Mass" };  
  9.    
  10. CreateFilter(f1);  
The following shows how the object is saved in the database.

saved in the database

Retrieving all the filters from the database

The "GetAllFilters()" method selects the records from the table, converts the serialized XML to objects again and returns a list of CustomFilters.
  1. public List<CustomFilter> GetAllFilters()  
  2. {  
  3.     string sql = "select FilterId,UserID,FilterDescription,Filters from tbl_filters";  
  4.    
  5.     DBUtil db = new DBUtil();  
  6.     List<CustomFilter> filters = new List<CustomFilter>();  
  7.    
  8.     db.DBConnect();  
  9.    
  10.     SqlDataReader myReader = db.FetchData(sql);  
  11.    
  12.    
  13.     while (myReader.Read())  
  14.     {  
  15.         var sFilter = myReader["filters"].ToString();  
  16.         CustomFilter filter = Utils.XMLToObject<CustomFilter>(sFilter);  
  17.         filters.Add(filter);  
  18.     }  
  19.    
  20.     db.DBDisconnect();  
  21.    
  22.     return filters;  
  23. }  
filters

Scenario 2: Passing serialized XML to SQL Server and selecting from XML Object in Stored Procedure

In this scenario, the user has a timesheet containing several tasks.

Instead of making several database calls to save each task, the complete timesheet object was serialized and passed to a Stored Procedure where the insert was done.

In the Stored Procedure, a select is made in the XML object to get the required information that is saved in a specific table based on its type.

The model

A timesheet has a list of tasks for each day.
  1. [Serializable]  
  2. public class Timesheet  
  3. {  
  4.     public DateTime TimesheetDate { getset; }  
  5.     public List<Task> Tasks;  
  6.    
  7.     public Timesheet()  
  8.     {  
  9.         Tasks = new List<Task>();  
  10.     }  
  11.    
  12.    
  13.     public override bool Equals(object obj)  
  14.     {  
  15.         if (obj == null)  
  16.             return false;  
  17.         var t = obj as Timesheet;  
  18.         if (t == null)  
  19.             return false;  
  20.         if (TimesheetDate == t.TimesheetDate)  
  21.             return true;  
  22.         return false;  
  23.     }  
  24.    
  25.     public override int GetHashCode()  
  26.     {  
  27.         int hash = 13;  
  28.         hash += (hash * 31) + TimesheetDate.GetHashCode();  
  29.    
  30.         return hash;  
  31.    
  32.     }  
  33. }  
  34.    
  35. [Serializable]  
  36. public class Task  
  37. {  
  38.     public int TaskID { getset; }  
  39.     public string TaskDescription { getset; }  
  40.     public string TaskType { getset; }  
  41.     public DateTime StartTime { getset; }  
  42.     public DateTime EndTime { getset; }  
  43.    
  44.    
  45.     public override bool Equals(object obj)  
  46.     {  
  47.         if (obj == null)  
  48.             return false;  
  49.         var t = obj as Task;  
  50.         if (t == null)  
  51.             return false;  
  52.         if (TaskID == t.TaskID)  
  53.             return true;  
  54.         return false;  
  55.     }  
  56.    
  57.     public override int GetHashCode()  
  58.     {  
  59.         int hash = 13;  
  60.         hash += (hash * 31) + Task.GetHashCode();  
  61.         return hash;  
  62.     }  
  63. }  
Creating and saving a timesheet
  1. List<Task> tasks = new List<Task>();  
  2. tasks.Add(new Task {  TaskType="Software Development", TaskDescription = "Analysis", StartTime = DateTime.Parse("23-10-2014 10:00:00"), EndTime = DateTime.Parse("23-10-2014 11:00:00") });  
  3. tasks.Add(new Task {  TaskType = "Software Development", TaskDescription = "Coding", StartTime = DateTime.Parse("23-10-2014 11:00:00"), EndTime = DateTime.Parse("23-10-2014 13:00:00") });  
  4. tasks.Add(new Task {  TaskType = "Software Development", TaskDescription = "Unit Test", StartTime = DateTime.Parse("23-10-2014 13:00:00"), EndTime = DateTime.Parse("23-10-2014 14:00:00") });  
  5. tasks.Add(new Task {  TaskType = "Administrative", TaskDescription = "Meeting", StartTime = DateTime.Parse("23-10-2014 14:00:00"), EndTime = DateTime.Parse("23-10-2014 15:00:00") });  
  6.    
  7. Timesheet DailyTimesheet = new Timesheet { TimesheetDate = DateTime.Today, Tasks = tasks };  
  8.    
  9.    
  10. CreateTimesheet(DailyTimesheet);  
The CreateTimesheet method takes a timesheet object as parameter, serializes the object and passes it to the procedure "feed_timesheet".
  1. public void CreateTimesheet(Timesheet timesheet)  
  2. {  
  3.     var TimesheetXML = Utils.ObjectToXMLGeneric<Timesheet>(timesheet);  
  4.    
  5.     DBUtil db = new DBUtil();  
  6.    
  7.     SqlCommand cmd = new SqlCommand("feed_timesheet");  
  8.     cmd.Parameters.Add("@Timesheet", SqlDbType.Xml).Value = TimesheetXML;  
  9.    
  10.     db.DBConnect();  
  11.    
  12.     var result = db.XmlInsertUpdate(cmd);  
  13.    
  14.     db.DBDisconnect();  
  15.    
  16. }  
Selecting from the XML and performing insert from Stored Procedure in SQL Server

From the procedure, the information must be filtered into "productive" and "non-productive" that goes into various tables.

The information is then inserted into the tables by selecting directly from the XML Object.
  1. CREATE PROCEDURE [dbo].[feed_timesheet]  
  2. @Timesheet XML  
  3.    
  4. AS  
  5. BEGIN  
  6.     -- SET NOCOUNT ON added to prevent extra result sets from  
  7.     -- interfering with SELECT statements.  
  8.     SET NOCOUNT ON;  
  9.    
  10. DECLARE @TimesheetDate varchar(10);  
  11.    
  12. SET @TimesheetDate =  cast(@Timesheet.query('data(Timesheet/TimesheetDate)'as varchar);  
  13.    
  14. INSERT INTO [dbo].[tbl_timesheet_productive]  
  15. (  
  16.     [TimesheetDate],  
  17.     [TaskDescription],  
  18.     [StartTime],  
  19.     [EndTime]    
  20. )  
  21. SELECT  
  22.     @TimesheetDate,  
  23.     cast(colx.query('data(TaskDescription) 'as varcharas description,  
  24.     cast(colx.query('data(StartTime) 'as varchar)  as starttime,  
  25.     cast(colx.query('data(EndTime) 'as varchar)  as endtime  
  26.    
  27. FROM @Timesheet.nodes('Timesheet/Tasks/Task'AS Tabx(Colx)  
  28. WHERE cast(colx.query('data(TaskType) ')  as varchar ) = 'Software Development';  
  29.    
  30.    
  31. INSERT INTO [dbo].[tbl_timesheet_nonproductive]  
  32. (  
  33.     [TimesheetDate],  
  34.     [TaskDescription],  
  35.     [StartTime],  
  36.     [EndTime]    
  37. )  
  38. SELECT  
  39.     @TimesheetDate,  
  40.     cast(colx.query('data(TaskDescription) 'as varcharas description,  
  41.     cast(colx.query('data(StartTime) 'as varchar)  as starttime,  
  42.     cast(colx.query('data(EndTime) 'as varchar)  as endtime  
  43.    
  44. FROM @Timesheet.nodes('Timesheet/Tasks/Task'AS Tabx(Colx)  
  45. WHERE cast(colx.query('data(TaskType) ')  as varchar ) = 'Administrative';  
  46.    
  47. END  
  48.    
  49. GO  

 

Up Next
    Ebook Download
    View all
    Learn
    View all