Microsoft KB Archive/316730

From BetaArchive Wiki

Article ID: 316730

Article Last Modified on 5/18/2007



APPLIES TO

  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0



This article was previously published under Q316730


This article refers to the following Microsoft .NET Framework Class Library namespaces:

  • System.Xml.Serialization
  • System.IO

IN THIS TASK

SUMMARY

REFERENCES

SUMMARY

This article demonstrates how to use the System.XmlSerialization.XmlSerializer class to serialize and to deserialize an object to Extensible Markup Language (XML).

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:

  • Microsoft Visual Studio .NET

This article assumes that you are familiar with the following topics:

  • Microsoft Visual Basic .NET
  • XML

back to the top

Description of XML Serialization

Serialization is the process by which you store an object's state in a stream of data. Serialization allows you to persist an object's state so that you can retrieve the state later. Serialization also allows you to clone an existing object to create a new object. The System.Xml.Serialization namespace contains classes that you can use to serialize objects into XML.

back to the top

Create the Console Application in Visual Basic .NET

In this section, you create a console application that:

  • Deserializes an object to XML.
  • Saves the XML serialization to a text file.
  • Reads the XML in the text file to create a new object (deserialization).
  1. Follow these steps to create a new console application in Visual Basic .NET:
    1. Start Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Console Application under Templates.
  2. Follow these steps to add a new class to the project:
    1. On the Project menu, click Add Class.
    2. In the Add New Item dialog box, type clsProduct.vb in the Name text box, and then click Open.
  3. Replace the code in the clsProduct.vb code window with the following code:

    Public Class clsProduct
    
      Private mstrName As String
      Private mstrDescription As String
      Private mintQty As Integer
    
      Public Property Name() As String
        Get
          Name = mstrName
        End Get
        Set(ByVal Value As String)
          mstrName = Value
        End Set
      End Property
    
      Public Property Description() As String
        Get
          Description = mstrDescription
        End Get
        Set(ByVal Value As String)
          mstrDescription = Value
        End Set
      End Property
    
      Public Property Qty() As Integer
        Get
          Qty = mintQty
        End Get
        Set(ByVal Value As Integer)
          mintQty = Value
        End Set
      End Property
    
    End Class
                            

    This code creates a Product class with three properties: Name, Description, and Qty (quantity).

  4. Switch to the code window for Module1.vb, and then add the following code to the top of the code window:

    Imports System.IO
    Imports System.Xml.Serialization
                        
  5. In the Sub Main procedure, add the following code to create and to populate an instance of the clsProduct class:

        'Set up product object.
        Dim p As New clsProduct()
        p.Name = "Widget"
        p.Description = "Faster, better, cheaper"
        p.Qty = 5
                        
  6. Use the XmlSerializer object to serialize the object to XML and to save the object's state to a text file. To do this, add the following code immediately before the End Sub statement in the Sub Main procedure:

        'Serialize object to a text file.
        Dim objStreamWriter As New StreamWriter("C:\Product.xml")
        Dim x As New XmlSerializer(p.GetType)
        x.Serialize(objStreamWriter, p)
        objStreamWriter.Close()
                        
  7. On the Debug menu, click Start to run the application.
  8. Open the Product.xml file in Notepad or in Microsoft Internet Explorer. The contents of this file should appear as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <clsProduct xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Name>Widget</Name>
      <Description>Faster, better, cheaper</Description>
      <Qty>5</Qty>
    </clsProduct>
                            
  9. The Xml.Serialization namespace enables you to customize the output that the XmlSerializer class generates. For example, in the clsProduct class, the quantity field is abbreviated as Qty. You can use the XmlElementAttribute attribute to change the field to Quantity when you serialize the class.

    Switch to the code window for clsProduct.vb, and then add the following code to the top of the code window:

    Imports System.Xml.Serialization
                        
  10. Locate the property procedure for Qty, and then insert the following code immediately before the Public Property Qty() As Integer statement:

    <XmlElementAttribute(ElementName:="Quantity")> _
                        
  11. On the Debug menu, click Start to run the application.
  12. Open the Product.xml file in Notepad or in Internet Explorer. The contents of this file should appears as follows:
    <?xml version="1.0" encoding="utf-8"?>
    <clsProduct xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Name>Widget</Name>
      <Description>Faster, better, cheaper</Description>
      <Quantity>5</Quantity>
    </clsProduct>
                                
    Notice that the Qty element changed to Quantity.
  13. Switch to the code window for Module1.vb, and then add the following code to the Sub Main procedure immediately before the End Sub statement:

        'Deserialize text file to a new object.
        Dim objStreamReader As New StreamReader("C:\Product.xml")
        Dim p2 As New clsProduct()
        p2 = x.Deserialize(objStreamReader)
        objStreamReader.Close()
    
        'Display property values of the new product object.
        Console.WriteLine(p2.Name)
        Console.WriteLine(p2.Description)
        Console.WriteLine(CStr(p2.Qty))
        Console.ReadLine()
                            

    This code deserializes the Product.xml text file to create a new clsProduct object named p2. In addition, this code displays the property values of p2 in the Console window.

back to the top

Verify That It Works

On the Debug menu, click Start to run the application. Notice that the property values of p2 appear in the Console window:

Widget
Faster, better, cheaper
5
                    

back to the top

Complete Code Listing

'Module1.vb
Imports System.Xml.Serialization
Imports System.IO

Module Module1

  Sub Main()
    
    'Set up product object.
    Dim p As New clsProduct()
    p.Name = "Widget"
    p.Description = "Faster, better, cheaper"
    p.Qty = 5

    'Serialize object to a text file.
    Dim objStreamWriter As New StreamWriter("C:\Product.xml")
    Dim x As New XmlSerializer(p.GetType)
    x.Serialize(objStreamWriter, p)
    objStreamWriter.Close()

    'Deserialize text file to a new object.
    Dim objStreamReader As New StreamReader("C:\Product.xml")
    Dim p2 As New clsProduct()
    p2 = x.Deserialize(objStreamReader)
    objStreamReader.Close()

    'Display property values of the new product object.
    Console.WriteLine(p2.Name)
    Console.WriteLine(p2.Description)
    Console.WriteLine(CStr(p2.Qty))
    Console.ReadLine()

  End Sub

End Module

'clsProduct.vb
Imports System.Xml.Serialization

Public Class clsProduct

  Private mstrName As String
  Private mstrDescription As String
  Private mintQty As Integer

  Public Property Name() As String
    Get
      Name = mstrName
    End Get
    Set(ByVal Value As String)
      mstrName = Value
    End Set
  End Property

  Public Property Description() As String
    Get
      Description = mstrDescription
    End Get
    Set(ByVal Value As String)
      mstrDescription = Value
    End Set
  End Property

  <XmlElementAttribute(ElementName:="Quantity")> _
  Public Property Qty() As Integer
    Get
      Qty = mintQty
    End Get
    Set(ByVal Value As Integer)
      mintQty = Value
    End Set
  End Property

End Class
                

back to the top

Keywords: kbhowtomaster KB316730