将XML元素和子元素放入列表中

时间:2012-11-27 21:07:49

标签: c# xml linq

鉴于以下XML,我如何使用以下实现将每条记录读入对象列表(记录列表)?

class Record
{
   public string Name {get; set;}
   public List<Skill> Skills {get; set;}
}

class Skill
{
   public string SkillName {get; set;}
   public string SkillType {get; set;}
}

XML

<records>
   <record>
      <name>John</name>
      <skills>
         <skill>
            <skillname>Tennis</skillname>
            <skilltype>Sport</skilltype>
         </skill>
         <skill>
            <skillname>Violin</skillname>
            <skilltype>Music</skilltype>
         </skill>
      </skills>
   </record>
   <record>
      <name>Juanita</name>
      <skills>
         <skill>
            <skillname>Football</skillname>
            <skilltype>Sport</skilltype>
         </skill>
         <skill>
            <skillname>Pottery</skillname>
            <skilltype>Craft</skilltype>
         </skill>
      </skills>
   </record>
</records>

我尝试获得子元素(技能)并没有成功。

List<Records> records;
DataSet dstRecords = new DataSet();
dstRecords.ReadXml(file);

foreach (DataRow row in dstRecords.Tables[0].Rows)
            {

                Record record = new Record
                {
                    Name = Convert.ToString(row["name"]),
                    Skills = skills
                };
                records.Add(records);
            }

2 个答案:

答案 0 :(得分:1)

XDocument xDoc = XDocument.Parse(xmlstring); //or XDocument.Load(filename);
var list = xDoc.Descendants("record")
            .Select(r => new Record
            {
                Name = (string)r.Element("name"),
                Skills = r.Descendants("skill")
                           .Select(s=>new Skill{
                               SkillName = (string)s.Element("skillname"),
                               SkillType = (string)s.Element("skilltype"),
                           })
                           .ToList()
            })
            .ToList();

答案 1 :(得分:0)

假设您想要Linq-to-XML,您只需将所需的调用“链接”到ElementElements(或Descendants):

// assuming XDocument xdoc = ...
var records = from r in xdoc.Root.Elements("record")
              select new Record
              {
                  Name = (string)r.Element("name"),
                  Skills = (from s in r.Element("skills").Elements("skill")
                            select new Skill
                            {
                                SkillName = (string)s.Element("skillname"),
                                SkillType = (string)s.Element("skilltype")
                            }).ToList()
              };