将XML转换为通用列表

15

我正在尝试将XML转换为列表

<School>
  <Student>
    <Id>2</Id>
    <Name>dummy</Name>
    <Section>12</Section>
  </Student>
  <Student>
    <Id>3</Id>
    <Name>dummy</Name>
    <Section>11</Section>
  </Student>
</School>

我尝试使用LINQ做了几件事情,但对接下来该怎么做不是很清楚。

dox.Descendants("Student").Select(d=>d.Value).ToList();

我得到的计数是2,但值看起来像2dummy12 3dummy11

是否可能将上述XML转换为具有Id、Name和Section属性的通用类型Student的列表?

我可以如何最好地实现这个?


3
我认为这篇文章 使用LINQ将XML转换为对象 会很有用。 - Maryam Arshi
3个回答

19

我看到您已经接受了一个答案,但我想展示我喜欢的另一种方法。首先您需要以下类:

public class Student
{
    [XmlElement("Id")]
    public int StudentID { get; set; }

    [XmlElement("Name")]
    public string StudentName { get; set; }

    [XmlElement("Section")]
    public int Section { get; set; }
}

[XmlRoot("School")]
public class School
{
    [XmlElement("Student", typeof(Student))]
    public List<Student> StudentList { get; set; }
}

然后您可以对此XML进行反序列化:

string path = //path to xml file

using (StreamReader reader = new StreamReader(path))
{
    XmlSerializer serializer = new XmlSerializer(typeof(School));
    School school = (School)serializer.Deserialize(reader);
}

希望这会有所帮助。


我知道这个问题在9年前就已经有答案了,但是我刚刚找到了这个答案来解决一个问题,并且它非常有效。然而,我很好奇using代码块之后的StudentList属性是如何被填充的。在什么时候序列化程序会用学生对象填充这个属性列表? - Zayum

16

您可以创建一个匿名类型

var studentLst=dox.Descendants("Student").Select(d=>
new{
    id=d.Element("Id").Value,
    Name=d.Element("Name").Value,
    Section=d.Element("Section").Value
   }).ToList();

这将创建一个匿名类型的列表。


如果您想创建一个Student类型的列表

class Student{public int id;public string name,string section}

List<Student> studentLst=dox.Descendants("Student").Select(d=>
new Student{
    id=d.Element("Id").Value,
    name=d.Element("Name").Value,
    section=d.Element("Section").Value
   }).ToList();

那个完美地运行了。我怎么把它转换成学生列表? - user2067567

1
var students = from student in dox.Descendants("Student")
           select new
            {
                id=d.Element("Id").Value,
                Name=d.Element("Name").Value,
                Section=d.Element("Section").Value
            }).ToList();

或者您可以创建一个名为Student的类,其中id、name和section是属性,然后执行以下操作:

var students = from student in dox.Descendants("Student")
           select new Student
            {
                id=d.Element("Id").Value,
                Name=d.Element("Name").Value,
                Section=d.Element("Section").Value
            }).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接