2013-01-23 74 views
2

結束我有這樣一個xml:錯誤:查詢體必須與SELECT子句或group子句

<countries> 
    <country ID="MX"> 
     <idea ID="Valor1">nota1</idea> 
     <idea ID="Valor2">nota2</idea> 
     <idea ID="Valor3">nota3</idea> 
     <idea ID="Valor4">nota4</idea> 
    </country> 
    <country ID="US"> 
     <idea ID="Valor1">nota1</idea> 
     <idea ID="Valor2">nota2</idea> 
     <idea ID="Valor3">nota3</idea> 
     <idea ID="Valor4">nota4</idea> 
    </country> 
</countries> 

使用LINQ到XML我怎麼能得到特定類型的列表?我想是這樣的:

我創建了一個類:

public class Ideas 
{ 
    public string Country { get; set; } 

    public List<ListItem> ListIdeas { get; set; } 
} 

然後我使用這個類做一個列表:

XDocument xdoc = XDocument.Load(this.Server.MapPath("~/config/ideas.xml")); 

var cat = from p in xdoc.Descendants("countries") 
         .Elements("country") 
         .Select(m => new Ideas 
          { 
           Country = m.Attribute("ID").Value, 
           ListIdeas = m.Elements("idea") 
              .Select(c => 
               new ListItem 
               { 
                Text = c.Attribute("ID").Value , 
                Value = c.Value 
               }).ToList() 
          }); 

,但我得到了一個錯誤:

A query body must end with a select clause or a group clause

The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

回答

1

你在最後選擇丟失。請嘗試:

XDocument xdoc = XDocument.Load(this.Server.MapPath("~/config/ideas.xml")); 

List<Ideas> cat = from p in xdoc.Descendants("countries").Elements("country") 
         .Select(m => new Ideas 
          { 
           Country = m.Attribute("ID").Value, 
           ListIdeas = m.Elements("idea") 
           .Select(c => 
            new ListItem 
            { 
             Text = c.Attribute("ID").Value , 
             Value = c.Value 
            }).ToList() 
          }) select p; 
+0

國際海事組織,一個好的答案應該使用查詢語法或擴展方法的語法,他們中的一個,而不是一個組合。 – abatishchev

4

您可以混合使用查詢語法和擴展方法語法。選擇一個

var r = (from c in xdoc.Element("countries") 
         .Elements("country") 
     select new Country 
     { 
      ID = c.Attribute("ID").Value, 
      Ideas = (from i in c.Elements("idea") 
         select new Idea 
         { 
          Text = i.Attribute("ID").Value, 
          Value = i.Value 
         }).ToList() 
     }).ToList(); 

注意我將您的類和屬性重命名爲更好的可讀性。


同樣在另一種語法:

var q = xdoc.Element("countries") 
      .Elements("country") 
      .Select(c => new Country 
       { 
         ID = c.Attribute("ID").Value, 
         Ideas = c.Elements("idea") 
           .Select(i => new Idea 
            { 
             Text = i.Attribute("ID").Value, 
             Value = i.Value 
            }) 
           .ToList() 
       }) 
      .ToList(); 
相關問題