Microsoft KB Archive/323503

From BetaArchive Wiki
Knowledge Base


WebCast: XML Serialization and sample code

Article ID: 323503

Article Last Modified on 2/24/2006



APPLIES TO

  • Support WebCast
  • Microsoft .NET Framework Class Libraries 1.0
  • Microsoft .NET Framework Class Libraries 1.1



This article was previously published under Q323503

SUMMARY

This article serves as a pointer article to two XML Serialization Support WebCasts. Click the following links to access these WebCasts directly:

Support WebCast: Microsoft .NET Framework and XML Serialization May 30, 2002
http://support.microsoft.com/default.aspx?scid=/servicedesks/webcasts/wc053002/wcblurb053002.asp
Level:#200


Support WebCast: Microsoft .NET Framework and XML Serialization (Advanced) August 8, 2002
http://support.microsoft.com/default.aspx?scid=/servicedesks/webcasts/wc080802/wcblurb080802.asp
Level:#300


MORE INFORMATION

The following is sample code that demonstrates how to perform object serialization by using the XmlSerializer. The code demonstrates some of the advanced techniques, such as complex object serialization, and the use of attributes in XML Serialization. The code also demonstrates the use of SOAP and Binary formatters. For a detailed description of these techniques, see the WebCast links that are listed in the "Summary" section of this article.

  1. Start Microsoft Visual Studio .NET. On the File menu, click New, and then click Project.
  2. Under Project Types, click Visual C# Projects, and then under Templates, click Console Application. By default, Class1.cs is created.
  3. In Class1.cs, replace the code with the following code:

    using System;
    using System.IO;
    using System.Xml.Serialization;
    using System.Xml;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    
    
    namespace SerializationWebCast
    {
        //[Serializable] attribute is for SOAP and binary formatters.
        [Serializable]
        public class Team
        {   //for SOAP serialization
            [SoapAttribute (Namespace="http://example.microsoft.com/Teams")]
            public string TeamID;
            public string TeamLeader;
            
            //This field is ignored during the serialization.
            [XmlIgnore]
            public string TeamName = "PrivateName";
        }
        
        public class EngineeringTeam : Team
        {
            public string TeamSecretCode;
            public int TotalTeamMembers;
            public bool BeenToMoon;
        }
    
        
        //Notice the use of XmlRootAttribute.
        [XmlRootAttribute(Namespace="http://www.blahfakeProjects.com.xml",
        ElementName = "CoolProjects", IsNullable = false)]
    
        public class Project
        {
        
            public Team OwnerTeam;
            public Team [] PastTeams;
        
            //Notice the use of XmlAttribute attribute, this field is
            //serialized as an attribute. 
            [XmlAttribute("MissionCode")]
            public int ProjectID;
    
            public Project()
            {
                OwnerTeam = new Team();
                OwnerTeam.TeamID = "111";
                OwnerTeam.TeamLeader = "Mr.Narayanan";
            }
    
        }
    
        class MainClass
        {
            [STAThread]
            static void Main(string[] args)
            {
    
                //Initialize simple Team Object.
                Team T = new Team(); 
                T.TeamID = "WEBNC23"; 
                T.TeamLeader = "Suchitra Mohan";
            
                //SIMPLE SERIALIZATION
                XmlSerializer srz = new System.Xml.Serialization.XmlSerializer(T.GetType());
                //create media writer
                TextWriter wt = new StreamWriter(@"..\WEBNC23.xml");
                srz.Serialize(wt,T);
                //Close writer so others can use the file. 
                wt.Close();
    
                //SIMPLE DESIRIALIZATION -- deserialize the previously serialized object.
                XmlSerializer dsrz = new System.Xml.Serialization.XmlSerializer(typeof(Team));
                TextReader tr = new StreamReader(@"..\WEBNC23.xml");
                Team T2 = (Team)dsrz.Deserialize(tr);
                
                //T2 as a normal object again. 
                Console.WriteLine("{0}, {1}",T2.TeamID,T2.TeamLeader);
    
                //Example of complex field serialized. 
                Project P = new Project();
                P.ProjectID = 23123;
                XmlSerializer srz2 = new System.Xml.Serialization.XmlSerializer(typeof(Project));
                Stream strm = File.Open(@"..\complexTeam.xml", FileMode.OpenOrCreate,FileAccess.ReadWrite);
                srz2.Serialize(strm,P);
                
                //Example of inheritance serialized.
                EngineeringTeam ET = new EngineeringTeam();
                ET.BeenToMoon = true;
                ET.TeamID = "WEBWA231";
                ET.TeamSecretCode = "01101x";
                ET.TotalTeamMembers = 23;
    
                XmlSerializer srz3 = new System.Xml.Serialization.XmlSerializer(typeof(EngineeringTeam));
                Stream strm3 = File.Open(@"..\ET.xml", FileMode.OpenOrCreate,FileAccess.ReadWrite);
                srz3.Serialize(strm3,ET);
                
                //Array of Objects Serialized, notice PastTeams object.
                Project p = new Project();
                p.PastTeams = new Team[2];
                p.PastTeams[0] = new Team();
                p.PastTeams[1] = new Team();
    
                p.PastTeams[0].TeamID = "F423";
                p.PastTeams[0].TeamLeader = "MYTHREE";
                p.PastTeams[1].TeamID= "H213";
                p.PastTeams[1].TeamLeader = "GYTHREE";
    
                XmlSerializer srz4 = new System.Xml.Serialization.XmlSerializer(typeof(Project));
                Stream strm4 = File.Open(@"..\Array.xml", FileMode.OpenOrCreate,FileAccess.ReadWrite);
                srz4.Serialize(strm4,p);
    
                //SOAP serialization with XmlSerializer
                XmlTypeMapping xtp = ( new SoapReflectionImporter().ImportTypeMapping(typeof(Team)));
                XmlSerializer sr2 = new XmlSerializer(xtp);
                Team T5 = new Team(); 
                T5.TeamID = "PKFSD"; 
                T5.TeamLeader = "Ajay Solanki";
                TextWriter wt2 = new StreamWriter(@"..\PKFSD.xml");
                sr2.Serialize(wt2,T5);
    
                //SOAP Serialization with SOAP formatter.
                SoapFormatter sf = new SoapFormatter();
                Stream strm6 = File.Open(@"..\SOAP.xml", FileMode.OpenOrCreate,FileAccess.ReadWrite);
                sf.Serialize(strm6,T5);
    
                //BINARY Serialization with BINARY formatter.
                BinaryFormatter bf = new BinaryFormatter();
                Stream strm7 = File.Open(@"..\Binary.bin", FileMode.OpenOrCreate,FileAccess.ReadWrite);
                bf.Serialize(strm7,T5);
                
    
            }//End of main.
        }//End of MainClass.
    }//End of SerializationWebCast namespace.
                            
  4. On the Project menu, click Add Reference, and then click System.Runtime.Serialization.Formatters.Soap from the list box.
  5. Compile the project. Notice that all the output files that are created are placed in the Bin folder of the application.

    Note Read the comments in the code for a better understanding.

All the code samples in the WebCasts are covered in the code that is included in this article. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

314150 Roadmap for XML Serialization in the .NET Framework


Support WebCasts are a free Internet broadcast service. Support WebCasts are available to all Microsoft customers. Tune in and watch live technical presentations that are given by Microsoft technology experts and participate in live Q&A sessions. Within 24 hours of the live broadcast, on-demand streaming media content is made available for playback.

For additional information about all the upcoming Support WebCasts, or to download related materials, visit the following Microsoft Web site:


Note The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, places, or events is intended or should be inferred.

Keywords: kbinfo KB323503