Sunday, September 15, 2013

How to read XML file

   Create an XML file named StudentData.xml.
Like this
<?xml version="1.0" encoding="utf-8" ?>

<Students>

 <Student>

 <name>Jamal</name>

 <class>six</class>

 </Student>

 <Student>

 <name>Kamal</name>

 <class>Seven</class>

 </Student>

 <Student>

 <name>Salam</name>

 <class>six</class>

 </Student>

 <Student>

 <name>Tomal</name>

 <class>six</class>

 </Student>

 <Student>

 <name>Jalal</name>

 <class>Seven</class>

 </Student>

</Students>
After this
Create a class student like this
public class Student

 
 
{

 
 private string name;

public string Name
 
 

{

 
 get { return name; }

set { name = value; }
 
 

}

 
 private string className;

public string ClassName
 
 

{

 
 get { return className; }

set { className = value; }
 
 

}

}
 
After that write the following line to read the StudentData.xml
 
XmlReaderSettings settings = new XmlReaderSettings();

settings.IgnoreComments = false;

settings.IgnoreWhitespace = true;

XmlTextReader xtr = new XmlTextReader(Server.MapPath("StudentData.xml"));

XmlDocument doc = new XmlDocument();


doc.Load(xtr);


 XmlNodeList nodeList = doc.SelectNodes("//Student");


Student _stu = null;

IList<Student> _studentList = new List<Student>();

foreach (XmlNode n in nodeList)


{


 _stu = new Student();


_stu.Name = n.ChildNodes[0].InnerText;

_stu. ClassName = n.ChildNodes[1].InnerText;

_studentList.Add(_stu);

}

GridView1.DataSource = _studentList;

GridView1.DataBind();