使用LinqToXML将XML映射到具有多个级别的c#对象

时间:2013-12-17 19:04:40

标签: c# xml linq-to-xml

我有一个xml文件,如下所示:

<Student>
    <Id> 10010</id>
    <Name>AAA</Name>
    <Gender>F</Gender>
    <Tags>
        <HobbyTags>
            <Tag>Reading</Tag>
            <Tag>Movies</Tag>
            <Tag>Jogging</Tag>
         </HobbyTags>
         <MajorTags>
            <Tag>Math</Tag>
            <Tag>Literature</Tag>
         </MajorTags> 
     </Tags>
</Student>
<Student>... </Student>
<Student>... </Student>
<Student>... </Student>

我有这样的c#对象:

public class Tag
{   
    public string tag {get; set;}
}
public class HobbyTags 
{
    List<Tag> hobbyTags {get; set;}
}
public class MajorTags 
{
    List<Tag> majorTags {get; set;}
}
public class Tags
{
    public HobbyTags hobbyTags {get; set;}
    public MajorTags majorTags {get; set;}
}
public class Student
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Gender {get; set;}
    public Tags tags {get; set;}
}

public class Students
{
    public List<Student> students {get; set;}
}

现在我使用linqToXML映射xml和c#对象,将xml中的值放入数据对象的相应字段中。我的问题是我知道如何设置第一级字段,如Id,Name,Gender,但我不知道如何设置内部级别的值,如HobbyTags,MajorTags。除了id之外,xml中的其他字段可以为null。任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

/*<Students>
<Student>
    <Id> 10011</Id>
    <Name>AAA</Name>
    .......
</Student>
</Students>
*/


var xdoc = XDocument.Load(@"C:\students.xml");
Students students = new Students();

students.students = xdoc.Descendants("Student").Select (x => new Student {
  Id = int.Parse(x.Element("Id").Value),
  Name = x.Element("Name").Value,
  Gender = x.Element("Gender").Value,
  tags = new Tags{
   hobbyTags = new HobbyTags{
    hobbyTags = x.Element("Tags").Element("HobbyTags").Descendants("Tag").Select (t => new Tag{ tag =  t.Value}).ToList()       
   },
   majorTags = new MajorTags{
    majorTags = x.Element("Tags").Element("MajorTags").Descendants("Tag").Select (t => new Tag{ tag =  t.Value}).ToList()       
   },
  }

}).ToList()

public class Tag
{   
    public string tag {get; set;}
}
public class HobbyTags 
{
   public List<Tag> hobbyTags {get; set;}
}
public class MajorTags 
{
    public List<Tag> majorTags {get; set;}
}
public class Tags
{
    public HobbyTags hobbyTags {get; set;}
    public MajorTags majorTags {get; set;}
}
public class Student
{
    public int Id {get; set;}
    public string Name {get; set;}
    public string Gender {get; set;}
    public Tags tags {get; set;}
}

public class Students
{
    public List<Student> students {get; set;}
}