XML Serializer/Deserializer C# .Net Example

XML Serializer – Sample Code – How to take a C# object and write it to a file in XML “serialized” format.

NOTE: Serialize means to take an object (in memory) and turn it to a format that can be preserved to disk (or sent over a wire). Deserialize means to take the serialized-format, and turn it back into an object (in memory).

Calling Program – to use Subroutine in Next Code Sample Below

<pre>
using System.Xml.Serialization;
using System.IO;
using System.Xml; 
...

//  Serialize an object in memory to disk. 

            XmlSerializer xs1 = new XmlSerializer(typeof(YourClassName));
            StreamWriter sw1 = new StreamWriter(@"c:DeserializeYourObject.xml");
            xs1.Serialize(sw1, objYourObjectFromYourClassName);
            sw1.Close();

// Now to deserialize it - assuming this might be a different program, run later.

            XmlSerializer xs2 = new XmlSerializer(typeof(YourClassName));
            StreamReader sr2 = new StreamReader(@"c:DeserializeYourObject.xml");
            // deserialize and cast back to proper class
            objYourObjectFromYourClassName = (YourClassName) xs2.Deserialize(sr2);
            sr2.Close();
            Console.WriteLine ("Deserialize2 completed");

</pre>

NOTE: Serializing to a string in memory is a lot trickier than you might think, because you have to deal with byteArrays, and encoding. Here’s a link to a page that explains how to do it:

XMLHelper Class Library – with SerializeObject and DeserializeObject


http://www.dotnetjohn.com/articles.aspx?articleid=173

Based on the above article, I put the following code in my “Common” C# Component library that is deployed on all my systems:

<pre>
        /// <summary>
        /// Method to convert a custom Object to XML string
        /// </summary>
        /// Object that is to be serialized to XML
        /// XML string
        public static String SerializeObject(Object pObject)
        {

            try
            {

                String XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(pObject.GetType());
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObject);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return XmlizedString;

            }

            catch (Exception e)
            {
                System.Console.WriteLine(e);
                return null;
            }

        }
        /// <summary>
        /// Method to reconstruct turn XMLString back into Object
        /// </summary>
        /// 
        /// 

        public static Object DeserializeObject(String pXmlizedString, Type classType)
        {

            XmlSerializer xs = new XmlSerializer(classType);
            MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            return xs.Deserialize(memoryStream);

        }

        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private static Byte[] StringToUTF8ByteArray(String pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }

</pre>

Just wrap the above with your class name, and add these using statements:

<pre>
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Xml.Schema;
using System.IO;
using System.Xml.Serialization;
using System.Text;
</pre>

Added June 2020

Example C# Class To Serialize

The object to be serialized is created from the PurchaseOrder850 class below. This class happens to represent a EDI 850 Purchase Order, but same concept works with any class. This is shows a two level hierarchy, where one Purchase Order has many line items. So the first class (PurchaseOrder850) references the second class (PurchaseOrder850LineItem).

<pre>
    public class PurchaseOrder850
    {
        public string PONum;
        public string PODateText;
        public DateTime PODate; 
        public string POType;
        public string VendorNumber;
        public string BuyerName;
        public string BuyerTelephone; 
        public List<PurchaseOrder850LineItem> LineItems; 
    }
    public class PurchaseOrder850LineItem
    {
        public string lineItem;
        public int quantity;
        public string uom;
        public decimal price;
        public string basisOfUnitPrice;
        public string catalogNumber;
        public string description;
        public string dateRequiredTxt;
        public DateTime dateRequired; 
    }

</pre>

Example Serialized XML

<pre>
<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder850 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PONum>1234567890</PONum>
  <PODateText>20080827</PODateText>
  <PODate>2008-08-27T00:00:00</PODate>
  <POType>NE</POType>
  <VendorNumber>2046159</VendorNumber>
  <BuyerName>JANE WATSON</BuyerName>
  <BuyerTelephone>800-555-1234</BuyerTelephone>
  <LineItems>
    <PurchaseOrder850LineItem>
      <lineItem>00010</lineItem>
      <quantity>50</quantity>
      <uom>EA</uom>
      <price>47.06</price>
      <basisOfUnitPrice>HP</basisOfUnitPrice>
      <catalogNumber>CATCR50</catalogNumber>
      <description>CABLE RETAINER CLIP PLASTIC</description>
      <dateRequiredTxt>20080903</dateRequiredTxt>
      <dateRequired>2008-09-03T00:00:00</dateRequired>
    </PurchaseOrder850LineItem>
    <PurchaseOrder850LineItem>
      <lineItem>00020</lineItem>
      <quantity>200</quantity>
      <uom>EA</uom>
      <price>427.01</price>
      <basisOfUnitPrice>HP</basisOfUnitPrice>
      <catalogNumber>512</catalogNumber>
      <description>T-BAR *** BOX HANGER</description>
      <dateRequiredTxt>20080903</dateRequiredTxt>
      <dateRequired>2008-09-03T00:00:00</dateRequired>
    </PurchaseOrder850LineItem>
  </LineItems>
</PurchaseOrder850>
</pre>

Uncategorized