gpt4 book ai didi

C# XML 后代查询

转载 作者:行者123 更新时间:2023-11-30 22:37:06 25 4
gpt4 key购买 nike

这是我的 XML 结构,它是一个事件列表,每个事件都包含一个事件时间列表。我需要返回一个“TIME”值列表,但我一直在思考如何获取这些值(请注意,我需要查询此列表并按“Id”过滤)

enter image description here

到目前为止的代码:

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

最佳答案

关闭,您需要选择 <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

关于C# XML 后代查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6650426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com