0

给定以下 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);
            }
4

2 回答 2

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();
于 2012-11-27T21:13:39.600 回答
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()
              };
于 2012-11-27T21:10:50.250 回答