Thursday, July 13, 2017

Deserialize XML to C# object

In this post we will see the simple approach to deserialize XML to C# object.

Our XML String


string xmlString = "<Students><Student><Id>1</Id><Name>Manish Dubey</Name></Student><Student><Id>2</Id><Name>Pankaj</Name></Student></Students>";

Create our class


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

Create XML Serializer and StringReader Object


//First argument is type of object and second argument is root attribute of your XML string/source

  XmlSerializer serializer = new XmlSerializer(typeof(List<student>), new XmlRootAttribute("Students"));
  StringReader stringReader = new StringReader(xmlString);

At last, deserialize XMl to C# object


List<student> studentList = (List<student>)serializer.Deserialize(stringReader);

Output

deseralize-xml-to-c#-object
Add caption


No comments:

Post a Comment

^ Scroll to Top