0

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);
        }
Anuja Lamahewa
  • 897
  • 1
  • 11
  • 23
  • Is it fine if we use XMLSerializer in this? – Aizen Mar 30 '15 at 05:01
  • `StreamReader` is not used to parse XML file, it is for normal (unstructured) text files. Use `XmlDocument/XPath`, or [XDocument](http://www.dotnetcurry.com/showarticle.aspx?ID=564), or XML serializer. – kennyzx Mar 30 '15 at 05:12
  • XPathDocument doc = new XPathDocument(filePath); XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr; expr = nav.Compile("/STUDENT_INFO/STUDENT/NAME"); XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); Console.WriteLine(" Name " + nav2.Value); } @kennyzx The above code works. But how can I fill the list ?? – Anuja Lamahewa Mar 30 '15 at 05:17
  • **Add new created student instance to the list**. while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); `stuList.Add(new Student(){ Name = nav2.Value };);` – kennyzx Mar 30 '15 at 05:22

2 Answers2

0

You can linq your XML file directly

In your case

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();
Pradip Nadar
  • 272
  • 1
  • 4
0

2 Different Class. Student Class and Student Container Class. You can just call the Methods of StudentContainer class. Like Save or Load. or Load from text

using System.Xml;
using System.Xml.Serialization;

 public class Student
 { 
    [XmlElement("NAME")]
    public string Name;
    [XmlElement("AGE")]
    public int Age;


 }

 using System.Collections.Generic;
 using System.Xml;
 using System.Xml.Serialization;
 using System.IO;


[XmlRoot("STUDENT_INFO")]
public class StudentContainer()
{
  [XmlArrayItem("STUDENT")]
  public List<Student> Stu = new List<Student>();

   public void Save(string path)
    {
       var serializer = new XmlSerializer(typeof(StudentContainer));
       using(var stream = new FileStream(path, FileMode.Create))
       {
           serializer.Serialize(stream, this);
       }
}

public static StudentContainer Load(string path)
{
    var serializer = new XmlSerializer(typeof(StudentContainer));
    using(var stream = new FileStream(path, FileMode.Open))
    {
        return serializer.Deserialize(stream) as StudentContainer;
    }
}

     //Loads the xml directly from the given string. Useful in combination with www.text.
     public static StudentContainer LoadFromText(string text) 
{
    var serializer = new XmlSerializer(typeof(StudentContainer));
    return serializer.Deserialize(new StringReader(text)) as StudentContainer;
   }
}

Then use the List to itterate .Name or .Age. I guess you already know how to do it.

**UPDATE**

//To use this
StudentContainer myStudents;
myStudents = DictionaryList.Load("C: <- your path");
Aizen
  • 1,807
  • 2
  • 14
  • 28