我有一个加载到XElement的XML文件。我想计算既存在又满足某些条件的PollEvent子女的数量。我已经让代码工作来计算PollEvents的总数,但是当我来过滤这个列表时,我似乎无法调用。在那里,我相信这是由于.Elements返回(扩展){{1 }}
到目前为止,这是代码 - 我已经在评论中放置了我想要发生的事情。
IEnumerable<XElements>
下面的一些示例XML
public PollDayPoint LoadData(DateTime date)
{
PollDayPoint newDayPoint = new PollDayPoint();
newDayPoint.Date = date;
String filename = AlertLogging.CreateFileName(date);
XElement xmlDoc = XElement.Load(filename);
IEnumerable<XElement> sdis = xmlDoc.Elements("SDI");
IEnumerable<XElement> pollEvents = sdis.Elements("PollEvent");
//This works
int count = 0;
using (IEnumerator<XElement> enumerator = pollEvents.GetEnumerator())
while (enumerator.MoveNext())
count++;
newDayPoint.NumPolls = count;
//Now we want to get all poll events that match certain conditions
//Match those that have "Alert" children with attribute status="Sent"
//IEnumerable<XElement> alertEvents = sdis.Elements("PollEvent");
return newDayPoint;
}
答案 0 :(得分:3)
首先,您的计算更简单:
int count = pollEvents.Count();
但是,您应该能够通过extension method让Elements()
工作,并且您应该可以毫无问题地致电Where
,例如:
var alertEvents =
sdis.Elements("PollEvent")
.Where(x => x.Elements("Alert")
.Any(alert => (string) alert.Attribute("status") == "Sent")
);
如果这不起作用,你可以发布你得到的错误吗?
答案 1 :(得分:1)
扩展Jon的答案,这将是他解决方案的扩展方法:
namespace MyExtensions
{
public static class XElementsExtension
{
//Returns an IEnumerable of <PollEvent> having an "<Alert>" child element with attribute "status" == status
public static IEnumerable<XElement> FindElementsByStatus(this IEnumerable<XElement> list, string status)
{
return list.Elements("PollEvent")
.Where(x => x.Elements("Alert")
.Any(alert => (string)alert.Attribute("status") == status)
);
}
}
}
答案 2 :(得分:0)
使用linq查询表达式来操作它们:
var result = from el in XElement.Parse(data).Descendants("PollEvent")
where el.Element("Alert").Attribute("status").Value == "Sent"
select el;
newDayPoint.NumPolls = result.Count();