2012-11-27 121 views
0

鑑於以下XML,如何使用以下實現將每條記錄讀入對象列表(記錄列表)?獲取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); 
      } 

回答

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

你會如何綁定 「技巧」到列表框和「名稱」到文本框? – mack

0

假設你想LINQ到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() 
       };