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>), 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);
Comments
Post a Comment