【问题标题】:Reading an XML and populating a list [duplicate]读取 XML 并填充列表 [重复]
【发布时间】:2015-03-30 13:49:07
【问题描述】:

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

【问题讨论】:

  • 这里面用XMLSerializer可以吗?
  • StreamReader 不用于解析 XML 文件,它用于普通(非结构化)文本文件。使用XmlDocument/XPath,或XDocument,或XML 序列化程序。
  • XPathDocument doc = new XPathDocument(filePath); XPathNavigator 导航 = doc.CreateNavigator(); XPathExpression 表达式; expr = nav.Compile("/STUDENT_INFO/STUDENT/NAME"); XPathNodeIterator 迭代器 = nav.Select(expr); while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); Console.WriteLine("名称" + nav2.Value); @kennyzx 上面的代码有效。但是我该如何填写列表呢??
  • 将新创建的学生实例添加到列表中。 while (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); stuList.Add(new Student(){ Name = nav2.Value };);

标签: c# xml


【解决方案1】:

您可以直接链接您的 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();

【讨论】:

    【解决方案2】:

    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 迭代 .Name 或 .Age。我想你已经知道该怎么做了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2018-04-24
      相关资源
      最近更新 更多