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), new XmlRootAttribute("Students"));
  StringReader stringReader = new StringReader(xmlString);;

At last, deserialize XMl to C# object


List studentList = (List)serializer.Deserialize(stringReader);

Output

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


No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo