读取XML并填充列表

时间:2015-03-30 04:52:49

标签: c# xml

我有一名班级学生,我想阅读包含学生信息的xml文件,并将信息列入清单。 我的代码:

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; }
    }
}

我正在阅读以下xml文件:

<?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>

这是我的主要方法:

        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);
        }

我需要读取xml并将stu对象放到stuList中。 我怎么能这样做?

更新:我使用了我的Pradip Nadar提到的LINQ语句

        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);
        }

2 个答案:

答案 0 :(得分:0)

您可以直接使用XML文件

在你的情况下

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();

答案 1 :(得分:0)

2个不同的班级。学生班和学生容器班。您只需调用StudentContainer类的方法即可。喜欢保存或加载。或从文本加载

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;
   }
}

然后使用List来itterate .Name或.Age。我猜你已经知道该怎么做了。

**UPDATE**

//To use this
StudentContainer myStudents;
myStudents = DictionaryList.Load("C: <- your path");