Load XML into CLR Objects via LINQ in C#
I have some XML that I have loaded into an XDocument. My XML looks like the following:
<Items>
<Item Date="11/22/2010 9:05:23 PM" />
<Item Date="11/22/2010 9:05:39 PM" />
</Items>
Each Item
contains a DateTime
. I am loading this XML into an XDoc开发者_运维技巧ument using the following code:
string s = GetXml();
XDocument xml = XDocument.Parse(s);
I am trying to figure out how to load the Items
into a List<DateTime>
. Can somebody explain to me how to do this using LINQ and C#?
Thank you!
Not tested, but something like this should do the trick:
var list = (from item in xml.Root.Descendents("Item")
select DateTime.Parse(item.Attribute("Date").Value).ToList();
var query = xml.Root.Elements("Item").
Select(item => DateTime.Parse(item.Attribute("Date").Value));
List<DateTime> result = query.ToList();
You can use the following statement to create a list of Dates, you can use the explicit cast from XElement to DateTime instead of using DateTime.Parse
var dates = xml.Root.Elements("Item")
.Select(e => (DateTime)e.Attribute("Date")).ToList();
精彩评论