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 タイプの一般的な List に変換することは可能ですか?

これを実装する最良の方法は何ですか?

4

3 に答える 3

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

または、ID、名前、およびセクションをプロパティとして使用して 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();
于 2013-04-30T10:45:12.177 に答える