如何使用LINQ to XML创建对象列表?

use*_*480 2 c# linq linq-to-xml

我有一些入站XML,我试图用LINQ读取生成对象列表:

<SCResponse>
<link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=2&amp;limit=20" rel="next_page" title="Next"/>
<link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=1&amp;limit=20" rel="previous_page" title="Previous"/>
<RecordLimit>20</RecordLimit>
<Notifications>
    <Notification href="http://192.168.6.126:8001/affiliate/account/81/notifications/24">
        <NotificationDate>2013-03-15T16:41:37-05:00</NotificationDate>
        <NotificationDetails>Notification details 1</NotificationDetails>
        <Status>New</Status>
        <NotificationTitle>Test notification 1</NotificationTitle>
    </Notification>
</Notifications>
<RecordsReturned>1</RecordsReturned>
<StartingRecord>1</StartingRecord>
<TotalRecords>1</TotalRecords>
Run Code Online (Sandbox Code Playgroud)

我创建了一个简单的POCO对象来表示"通知":

public class Notification
{
    public System.DateTime notificationDate;

    public string notificationDetails;

    public string status;

    public string notificationTitle;

    public string href;
}
Run Code Online (Sandbox Code Playgroud)

我想读取传入的XML并创建一个对象列表.

List<Notification> notificationList; 

XElement x = XElement.Load(new StringReader(result));
if (x != null && x.Element("Notifications") != null)
{
    notificationList = x.Element("Notifications")
                .Elements("Notification")
                .Select(e => new Notification()
                .ToList();
}
Run Code Online (Sandbox Code Playgroud)

我真的不清楚'e'部分以及如何初始化一个新的Notification对象.你可以帮忙吗?

p.s*_*w.g 6

e仅仅是一个参数名通过考试的lambda表达式,new Notification().你可以像这样使用它:

notificationList = x.Element("Notifications")
                    .Elements("Notification")
                    .Select(e => new Notification()
                                 {
                                     href = (string)e.Attribute("href")
                                     notificationDetails = (DateTime)e.Element("NotificationDate")
                                     notificationDate = (string)e.Element("NotificationDetails")
                                     status = (string)e.Element("Status")
                                     notificationTitle = (string)e.Element("NotificationTitle")
                                 }
                    .ToList();
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢查询语法

notificationList =
    (from e in x.Element("Notifications").Elements("Notification")
     select new Notification()
            {
                href = (string)e.Attribute("href")
                notificationDetails = (DateTime)e.Element("NotificationDate")
                notificationDate = (string)e.Element("NotificationDetails")
                status = (string)e.Element("Status")
                notificationTitle = (string)e.Element("NotificationTitle")
            })
    .ToList();
Run Code Online (Sandbox Code Playgroud)