Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 读取XML并填充列表_C#_Xml - Fatal编程技术网

C# 读取XML并填充列表

C# 读取XML并填充列表,c#,xml,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 = val

我有一个班级的学生,我想读一个包含学生信息的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>

姓名1
1.
姓名2
2.
姓名3
3.
这是我的主要方法:

        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);
        }
string filePath=“C:\\StudentInfo.xml”;
XmlDocument doc=新的XmlDocument();
文档加载(文件路径);
StreamReader=新的StreamReader(文件路径);
字符串行=”;
字符串xmlValue=null;
学生stu=新学生();
List stuList=新列表();
而((line=reader.ReadLine())!=null)
{
如果(第行包含(“”))
{
XmlNodeList elemList=doc.GetElementsByTagName(“名称”);
for(int i=0;i
我需要读取xml并将stu对象放入stu列表。 我该怎么做

更新:我用LINQ的声明提到了我的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);
        }
XDocument xdoc=XDocument.Load(“C:\\StudentInfo.xml”);
列出lv1s=(从xdoc.substands(“学生”)中的lv1开始)
选择新学生
{
Name=lv1.Element(“Name”).Value,
年龄=1级。元素(“年龄”)。值
}).ToList();
foreach(1年级学生)
{
Console.WriteLine(s.Name);
控制台写入线(s.Age);
}

您可以直接linq您的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();
XDocument xdoc=XDocument.Load(“C:\\StudentInfo.xml”);
列出lv1s=(从xdoc.substands(“学生”)中的lv1开始)
选择新学生
{
Name=lv1.Element(“Name”).Value,
年龄=1级。元素(“年龄”)。值
}).ToList();

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;
   }
}
使用System.Xml;
使用System.Xml.Serialization;
公立班学生
{ 
[XmlElement(“名称”)]
公共字符串名称;
[XmlElement(“年龄”)]
公共信息;
}
使用System.Collections.Generic;
使用System.Xml;
使用System.Xml.Serialization;
使用System.IO;
[XmlRoot(“学生信息”)]
公共类StudentContainer()
{
[XmlArrayItem(“学生”)]
公共列表Stu=新列表();
公共void保存(字符串路径)
{
var serializer=newxmlserializer(typeof(StudentContainer));
使用(var stream=newfilestream(路径,FileMode.Create))
{
serializer.Serialize(流,this);
}
}
公共静态StudentContainer加载(字符串路径)
{
var serializer=newxmlserializer(typeof(StudentContainer));
使用(var stream=newfilestream(路径,FileMode.Open))
{
返回序列化程序。反序列化(流)为StudentContainer;
}
}
//直接从给定字符串加载xml。与www.text结合使用非常有用。
公共静态StudentContainer LoadFromText(字符串文本)
{
var serializer=newxmlserializer(typeof(StudentContainer));
返回serializer.Deserialize(新的StringReader(文本))作为StudentContainer;
}
}
然后使用该列表记录.Name或.Age。我想你已经知道怎么做了

**UPDATE**

//To use this
StudentContainer myStudents;
myStudents = DictionaryList.Load("C: <- your path");
**更新**
//用这个
学生容器;

myStudents=DictionaryList.Load(“C:如果我们在这里使用XMLSerializer可以吗?
StreamReader
不用于解析XML文件,它用于普通(非结构化)文本文件。使用
XmlDocument/XPath
,或XML serializer.XPathDocument doc=new XPathDocument(filePath);XPathNavigator nav=doc.CreateNavigator();XPathExpression expr;expr=nav.Compile(“/STUDENT_INFO/STUDENT/NAME”);XPathNodeIterator=nav.Select(expr);while(iterator.MoveNext()){XPathNavigator nav2=iterator.Current.Clone();Console.WriteLine(“NAME”+nav2.Value);}@kennyzx上面的代码是有效的。但是我如何填充列表?将新创建的学生实例添加到列表中。while(iterator.MoveNext(){XPathNavigator nav2=iterator.Current.Clone();
stuList.Add(new student(){Name=nav2.Value};);