how to serialize an object to XML, and vice versa

Hi,

Here is code sample of Serializing and Deserializing.There is also some additional methods to convert Byte Array in the sample.

i use serialize and deserialize actions by generic in C#



private Byte[] StringToUTF8ByteArray(String pXmlString)   
    {   
     UTF8Encoding encoding = new UTF8Encoding();   
     //UTF8Encoding is under the System.Text namespace   
     Byte[] byteArray = encoding.GetBytes(pXmlString);   
     return byteArray;   
    }   
    private String UTF8ByteArrayToString(Byte[] characters)   
    {   
     UTF8Encoding encoding = new UTF8Encoding();   
     String constructedString = encoding.GetString(characters);   
     return (constructedString);   
    }   
    private string Serialize(T request)   
    {   
     //MemoryStream is in System.IO   
     //XMLSerializer is in System.Xml.Serialization   
     using (MemoryStream memoryStream = new MemoryStream())   
     {   
      XmlSerializer xs = new XmlSerializer(typeof(T));   
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
      xs.Serialize(xmlTextWriter, request);   
      return UTF8ByteArrayToString(memoryStream.ToArray());   
     }   
    }   
    private T Deserialize (string XmlizedString)    
    {   
     using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(XmlizedString)))   
     {   
      XmlSerializer xs = new XmlSerializer(typeof(T));   
      return (T) xs.Deserialize(memoryStream);   
     }   
    }   


You can also tag  any member of the class or struct to be shown in XML.
XMLAttribute marks the member as composite class,XMLElement marks the member as value of node as well

if you remark the struct as shown below;

 [Serializable]
    public class Group
    {
        [System.Xml.Serialization.XmlAttribute("id")]
        public Guid GroupId;

        [System.Xml.Serialization.XmlAttribute("text")]
        public string Text;

        [System.Xml.Serialization.XmlAttribute("type")]
        public string Type;

        [System.Xml.Serialization.XmlElement(ElementName = "Question")]
        public List < question >  Questions;
    }

good luck.

Comments

Popular posts from this blog

Assembly Microsoft.Dynamics.Service.Plugins.dll can not be loaded. Dynamics CRM 365 Engine version 9 - CRM User creation error

Exception caught instantiating TERADATA report server extension SQL Reporting Services

Could not load file or assembly 'System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified at Configuration class initiation in CrmServiceHelper.cv