Simple deserialization of XML to C# object

Simple approach how to deserialize XML to C# object without attributes.

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>), new XmlRootAttribute("Products"));


4. Create StringReader object


StringReader stringReader = new StringReader(xmlString);


5. Finally, deserialize to your C# object


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

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


That's all.

Share on Twitter or Facebook or Google+