无效的初始化成员声明符C#LINQ

时间:2015-09-17 17:19:19

标签: c# asp.net xml linq xml-parsing

我有XML并需要解析它并通过LINQ创建对象

<?xml version="1.0"  encoding="UTF-8"?> 
 <Books>         
   <Book> 
    <ID> number </ID>
    <DateCreated> date </DateCreated>  
    <Pages>  
     <Page>      
        <PageID> string </PageID>  
        <PageNumber> number </PageNumber> 
     </Page>     

    <!-- ... more Page nodes here if present ...     --> 
    </Pages>     
  </Book> 
   <!-- ... more Book nodes here ...     --> 
</Books>

类:

public class BooksResponse
    {
        public Book[] Book_Items { get; set; }
    }

    public class Book
    {
        public int ID { get; set; }
        public string DateCreated { get; set; }
        public Page[] Pages { get; set; }
    }

    public class Page
    {
        public string PageID { get; set; }
        public int PageNumber { get; set; }
    }

和我的代码:

var booksResponse = xDocument
                            .Elements("Books")
                            .Select(x => new BooksResponse
                            {
                                Book_Items = x.Elements("Book")
                                .Select(c => new Book
                                {
                                    DateCreated = (string)c.Element("DateCreated"),
                                    ID = (int)c.Element("ID"),
                                    Pages => c.Elements("Pages")
                                    .Select(y => new Page
                                    {
                                        PageID = (string)y.Element("PageID"),
                                        PageNumber = (int)y.Element("PageNumber"),

                                    }).ToArray()

                                }).ToArray()

                            }).FirstOrDefault();

和近代码页数=&gt; c.Elements(“Pages”)

错误:

无效的初始化成员声明符。

我做错了什么,如何解决?

非常感谢!

2 个答案:

答案 0 :(得分:1)

根据您的XML,正确的语法是

Pages = c.Descendants("Page")
.Select(y => new Page
{
    PageID = (string)y.Element("PageID"),
    PageNumber = (int)y.Element("PageNumber"),

}).ToArray()

正如已经指出的那样,首先将=>修复为=。现在,元素Pages没有元素PageIDPageNumber。它们位于节点Page下。要获取Page个节点的列表,您可以使用Descendants("Page"),因为它们不是Book的直接子元素。

答案 1 :(得分:1)

您可以使用XmlSerializer

var xs = new XmlSerializer(typeof(BooksResponse));
BooksResponse books = (BooksResponse)xs.Deserialize(responseStream);

为您的班级BooksResponse

添加属性
[XmlRoot("Books")]
public class BooksResponse
{
    [XmlElement("Book")]
    public Book[] Book_Items { get; set; }
}

它适用于给定的xml。