如何使用LINQ to XML创建对象列表? [英] How do I use LINQ to XML to create a list of objects?
本文介绍了如何使用LINQ to XML创建对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用LINQ读取一些入站XML以生成对象列表:
I have some inbound XML that I am trying to read with LINQ to generate a list of objects:
<SCResponse>
<link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=2&limit=20" rel="next_page" title="Next"/>
<link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=1&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>
我创建了一个简单的POCO对象来表示通知":
And I've created a simple POCO object to represent a 'Notification':
public class Notification
{
public System.DateTime notificationDate;
public string notificationDetails;
public string status;
public string notificationTitle;
public string href;
}
,我想读取传入的XML并创建对象列表.
and I'd like to read the incoming XML and create a list of objects.
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();
}
我真的不清楚'e'部分以及如何初始化新的Notification对象.可以帮忙吗?
I'm really unclear about the 'e' part and how to initialize a new Notification object. Can ya help?
推荐答案
e
is just a parameter name your passing to the lambda expression, new Notification()
. You can use it like this:
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();
或者,如果您更喜欢查询语法
Or if you prefer query syntax
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();
这篇关于如何使用LINQ to XML创建对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文