2013-01-23 54 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(); 
相关问题