I have a class student and i want to read a xml file containing the student info and put the info to a list. My code:
internal class Student
{
private string name = null;
private string age = null;
private string age = null;
public string Name
{
get { return name; }
set { name = value; }
}
public string Age
{
get { return age; }
set { age = value; }
}
}
and i'm reading the following xml file:
<?xml version="1.0" encoding="UTF-8"?>
<STUDENT_INFO>
<STUDENT>
<NAME>Name_1</NAME>
<AGE>1</AGE>
</STUDENT>
<STUDENT>
<NAME>Name_2</NAME>
<AGE>2</AGE>
</STUDENT>
<STUDENT>
<NAME>Name_3</NAME>
<AGE>3</AGE>
</STUDENT>
</STUDENT_INFO>
And here is my main method:
string filePath = "C:\\StudentInfo.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
StreamReader reader = new StreamReader(filePath);
string line = "";
string xmlValue = null;
Student stu = new Student();
List<Student> stuList = new List<Student>();
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("<NAME>"))
{
XmlNodeList elemList = doc.GetElementsByTagName("NAME");
for (int i = 0; i < elemList.Count; i++)
{
xmlValue = elemList[i].InnerXml;
stu.Name = xmlValue;
Console.WriteLine(xmlValue);
}
}
stuList.add(stu);
}
I need to read the xml and put the stu objects to the stuList. How can I do that ?
UPDATE: I used LINQ statements mentioned my Pradip Nadar
XDocument xdoc = XDocument.Load("C:\\StudentInfo.xml");
List<Student> lv1s = (from lv1 in xdoc.Descendants("STUDENT")
select new Student
{
Name = lv1.Element("NAME").Value,
Age = lv1.Element("AGE").Value
}).ToList();
foreach (Student s in lv1s)
{
Console.WriteLine(s.Name);
Console.WriteLine(s.Age);
}