Serialize and Deserialize Objects Using Custom SOAP Format Attributes

Introduction

 The following code sample shows how to use XML serialization attributes such as SoapElement and SoapAttribute to generate custom SOAP format  in the resulting XML during sterilization. The code defines a class named Institute and applies and XML serialization attributes to its members to format the resulting XML while serializing an object of the Institute class.

Code

public class Institute
{
        //Soap Custom Attribute Declaration
        [SoapAttribute(AttributeName="Institute")]
        public string Name;
        [SoapElement(ElementName = "CorporateInstitute")]
        public string CorporateInstitute;
        [SoapIgnore]
        public string InstituteID;
 
        public override string ToString()
        {
            //return base.ToString();
            string send;
            send="\nInstitute Name:"+this.Name;
            send+="\nCorporate Institute:"+this.CorporateInstitute;
            send+="\nInstitueID :"+this.InstituteID;
            return send;
        }

        static void Main(string[] args)
        {
           
//Specify xml file path

            string file = "Institute.soap";
             XmlTypeMapping maping=(new SoapReflectionImporter().ImportTypeMapping(typeof(Institute)));

           //XML Serializer Class Declaration for serializing class institute

            XmlSerializer XS = new XmlSerializer(maping);                     
            Institute IS = new Institute();
            IS.Name = "NIIT";
            IS.InstituteID="2013";
            IS.CorporateInstitute="Ghatkopar"

            ////Declarating of text writer

            XmlTextWriter TW = new XmlTextWriter(file, Encoding.UTF8);
            TW.Formatting=Formatting.Indented;
            TW.WriteStartElement("InstituteInfo");          
            XS.Serialize(TW, IS); 
            TW.WriteEndElement();
            TW.Flush();
            TW.Close(); 

            XmlTextReader TR = new XmlTextReader(file);
            TR.ReadStartElement("InstituteInfo");
            Institute IS1 = (Institute)XS.Deserialize(TR);
            TR.ReadEndElement();
            TR.Close();
            Console.WriteLine(IS1);
            Console.ReadLine();
        }
  }

Ebook Download
View all
Learn
View all