Simple deserialization of XML to C# object

1. Prepare XML string

  string xmlString = "<Products><Product><Id>1</Id><Name>My XML product</Name></Product><Product><Id>2</Id><Name>My second product</Name></Product></Products>";

2. Prepare C# object

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

3. Create XML serializer

First argument is type of object you want to get and in second argument you specify root attribute of your XML source.

  XmlSerializer serializer = new XmlSerializer(typeof(List<Product>), newXmlRootAttribute("Products"));

4. Create StringReader object

  StringReader stringReader = new StringReader(xmlString);

5. Finally, deserialize to your C# object

  List<Product> productList = (List<Product>)serializer.Deserialize(stringReader);

You can use our StringReader as argument or StreamWriter for external xml file too.

That’s all.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s