[英]Select XML Elements after last matching Element
I have XML file that looks like: 我有看起来像的XML文件:
<Meal>
<MealName>Lunch</MealName>
<MealData>blahblahblah</MealData>
<MealTime>2015-03-12</MealTime>
</Meal>
<Meal>
<MealName>Dinner</MealName>
<MealData>lolololol</MealData>
<MealTime>2015-04-27</MealTime>
</Meal>
I'd like to select MealName and MealData of the last Meal instance. 我想选择最后一个Meal实例的MealName和MealData。
I can do everything else I need with simple LINQ queries just fine. 我可以用简单的LINQ查询来做我需要做的其他事情。 For example, to get data from last week's meals, I do:
例如,为了从上周的饭菜中获取数据,我这样做:
XElement noIdea = XElement.Load(".../.../meal.xml");
DateTime d = DateTime.Today.AddDays(-7);
int offset = d.DayOfWeek - DayOfWeek.Monday;
DateTime lastMonday = d.AddDays(-offset);
DateTime lastSunday = lastMonday.AddDays(6);
IEnumerable<XElement> idkMealTime =
from el in noIdea.Elements("Meal")
where DateTime.Compare(Convert.ToDateTime(el.Element("MealTime").Value), lastMonday) > 0 &&
DateTime.Compare(Convert.ToDateTime(el.Element("MealTime").Value), lastSunday) < 0
select el;
WhatHaveYouEaten(idkMealTime);
But this one is different and I can't figure it out. 但这是不同的,我无法弄清楚。
Help is appreciated. 感谢帮助。
Simply select the last meal element: 只需选择最后一餐元素:
var lastMeal = noIdea.Elements("Meal").Last();
As an aside, you can simply cast an element to DateTime
rather than converting the string value - eg (DateTime)el.Element("MealTime")
. (DateTime)el.Element("MealTime")
,您可以将元素简单地转换为DateTime
而不是转换字符串值-例如(DateTime)el.Element("MealTime")
。 This uses DateTime.Parse
internally with the correct styles as allowed in the XML specification. 这将内部使用
DateTime.Parse
并使用XML规范中允许的正确样式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.