Now here in this tutorial, I will explain how to read the data from XML document or file and deserialize into array or list object in .net using c# and vb with an example code snippet.
In my previous tutorials, I’d explained format json date into local date string, preview image before upload, tooltip example to show hide hint or help text using css3 transition and other more cracking tutorials on Asp.net here.
Following is sample XML data that I’ll load into list object:
<StudentCollection>
<Students>
<Student>
<Id>1</Id>
<Name>John Kinn</Name>
<Percentage>70%</Percentage>
</Student>
<Student>
<Id>2</Id>
<Name>Miller Smith</Name>
<Percentage>80%</Percentage>
</Student>
<Student>
<Id>3</Id>
<Name>Marshel Woods</Name>
<Percentage>89%</Percentage>
</Student>
</Students>
</StudentCollection>
As you can see from the above sample data, we need Id, Name, and Percentage for every student. So, we need to create the Student class file with all needed fields or properties that will collect and store data from the xml document.
Deserialize XML Document Data – [C#]
First create Student.cs class file and place following code in that file.
Namespace:
public class Student
{
[XmlElement(“Id”)]
public int Id { get; set; }
[XmlElement(“Name”)]
public string Name { get; set; }
[XmlElement(“Percentage”)]
public string Percentage { get; set; }
}
[Serializable()]
[XmlRoot(“StudentCollection”)]
public class StudentCollection
{
[XmlArray(“Students”)]
[XmlArrayItem(“Student”, typeof(Student))]
public Student[] Student { get; set; }
}
After adding namespace, you can use following code to read xml data and deserialize into object:
string path = Server.MapPath(“results.xml”);
XmlSerializer serializer = new XmlSerializer(typeof(StudentCollection));
System.IO.StreamReader reader = new System.IO.StreamReader(path);
students = (StudentCollection)serializer.Deserialize(reader);
Deserialize XML Document Data – [Vb.net]
First create Student.vb class file and place following code in that file.
Namespace:
Public Class Student
<XmlElement(“Id”)>
Public Property Id() As Integer
<XmlElement(“Name”)>
Public Property Name() As String
<XmlElement(“Percentage”)>
Public Property Percentage() As String
End Class
<Serializable(), System.Xml.Serialization.XmlRoot(“StudentCollection”)>
Public Class StudentCollection
<XmlArray(“Students”), XmlArrayItem(“Student”, GetType(Student))>
Public Property Student() As Student()
End Class
After adding namespace, you can use following code to read xml data and deserialize into object:
Dim path As String = Server.MapPath(“results.xml”)
Dim serializer As New XmlSerializer(GetType(StudentCollection))
Dim reader As New System.IO.StreamReader(path)
students = CType(serializer.Deserialize(reader), StudentCollection)
Any chance you could please add the code to console.write all student records and fields from the students collection PLEASE?