繁体   English   中英

将XML转换为通用列表

[英]Converting a XML to Generic List

我正在尝试将XML转换为List

<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类型的通用List?

实现此目的的最佳方法是什么?

我知道您已经接受了答案。 但是我只想展示我喜欢的另一种方式。 首先,您将需要以下类:

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

希望对您有所帮助。

您可以创建一个匿名类型

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

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


如果要创建学生类型列表

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

或者,您可以创建一个以id,name和section为属性的类调用Student并执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM