15

我正在尝试将 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 Properties 的 Student 类型的通用列表?

我可以实现这一点的最佳方法是什么?

4

3 回答 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);
}

希望它会有所帮助。

于 2013-04-30T11:17:36.133 回答
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();

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


如果要创建学生类型列表

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();
于 2013-04-30T10:26:49.133 回答
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();
于 2013-04-30T10:45:12.177 回答