这是我的XML结构,它是一个事件列表,每个事件都包含一个事件时间列表。我需要返回一个'TIME'值列表,但我仍然坚持如何获取这些值(请注意,我需要查询此列表并按'Id'过滤)
到目前为止
代码:
public IEnumerable<EventFeed> GetEventDatesByEventId(int eventId)
{
return (from feed in xmlDoc.Descendants("Event")
where (int)feed.Element("Id") == eventId
from ev in feed.Elements("Times")
select new EventFeed()
{
EventDate = (DateTime)ev.Element("Time")
}).ToList().OrderByDescending(x => x.EventDate);
}
感谢 KB
答案 0 :(得分:3)
关闭,您需要先选择<Times>
节点,或使用Descendants
,因为<Time>
低于EventTime
:
return (from feed in xmlDoc.Descendants("Event")
where (int)feed.Element("Id") == eventId
from et in feed.Element("Times").Elements("EventTime")
select new EventFeed()
{
EventDate = (DateTime)et.Element("Time")
}).ToList().OrderByDescending(x => x.EventDate);
样品:
string xml = @"<?xml version=""1.0"" ?>
<Events>
<Event>
<Id>542</Id>
<Times>
<EventTime>
<Time>2011-11-28T14:00:00</Time>
</EventTime>
<EventTime>
<Time>2011-11-30T10:00:00</Time>
</EventTime>
<EventTime>
<Time>2011-11-30T09:00:00</Time>
</EventTime>
</Times>
</Event>
</Events>";
int eventId = 542;
foreach (var evt in GetEvents(XDocument.Parse(xml), eventId)
{
Console.WriteLine("{0}", evt.EventDate);
}
输出:
11/30/2011 10:00:00
11/30/2011 09:00:00
11/28/2011 14:00:00
答案 1 :(得分:0)
这是直接的蝙蝠和未经测试但这样的事情可能会这样做,或者至少让你开始
xmlDoc.Descendants("Event")
.Where(ev => (int) ev.Element("Id") == eventId)
.SelectMany(ev => ev.Element("Times").Elements("EventTime")
.Select(et => et.Element("Time").Value));
您可以更改最终选择以构建EventFeed类,如下所示:
.Select(et => new EventFeed{EventDate = (DateTime)et.Element("Time").Value}));