load object from xml using xmlserializer in csharp

To load an object from an XML using XmlSerializer in C#, follow these steps:

  1. Create an instance of XmlSerializer class for your object type.

    main.cs
    XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
    
    64 chars
    2 lines
  2. Create a StreamReader object to read the XML file content.

    main.cs
    StreamReader reader = new StreamReader(@"C:\path\to\my\file.xml");
    
    67 chars
    2 lines
  3. Call the Deserialize method of the XmlSerializer object and cast the result to the type of your object.

    main.cs
    MyObject myObj = (MyObject)serializer.Deserialize(reader);
    
    59 chars
    2 lines
  4. Close the StreamReader object.

    main.cs
    reader.Close();
    
    16 chars
    2 lines

Here's an example of how it can be done:

main.cs
using System;
using System.IO;
using System.Xml.Serialization;

public class MyObject
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class Program
{
  public static void Main()
  {
    XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
    StreamReader reader = new StreamReader(@"C:\path\to\my\file.xml");
    MyObject myObj = (MyObject)serializer.Deserialize(reader);
    reader.Close();
    Console.WriteLine("Id: " + myObj.Id);
    Console.WriteLine("Name: " + myObj.Name);
  }
}
527 chars
23 lines

gistlibby LogSnag