简体   繁体   English

使用linq从XML文档中删除最近30天的节点

[英]Remove Last 30 Days Nodes from XML Document using linq

I have XML Document like 我有像XML文档

 <Records>
   <Record>
    <Event>Home Value Submits Page 2</Event>
    <Date>17-Mar-14 4:49:32 PM</Date>
   </Record>
   <Record>
    <Event>Hm Value Submits Hm Pg</Event>
    <Date>17-Mar-14 4:54:36 PM</Date>
   </Record>
 </Records>

I need to delete last 30 Days nodes from XML Document. 我需要从XML文档中删除最近30天的节点。

I am using this code but it's not working, 我正在使用此代码,但无法正常工作,

var xelement = XElement.Load(Server.MapPath("~/XMLStorage/DataBase.xml"));
var value30days =
    from nm in xelement.Elements("Record")
    where (DateTime)nm.Element("Date") <= DateTime.Now && (DateTime)nm.Element("Date") >= DateTime.Now.AddDays(-30)
    select nm;

foreach (XElement xEle in value30days)
{
    xEle.Remove();
}

xelement.Save(Server.MapPath("~/XMLStorage/DataBase.xml"));

Please Give some solutions. 请提供一些解决方案。

This is one of those fun problems caused by changing a collection while enumerating/querying it. 这是由枚举/查询时更改集合引起的有趣问题之一。 As soon as you try to remove the first item you break the query. 尝试删除第一个项目后,您便会中断查询。

Try this: 尝试这个:

    foreach (XElement xEle in value30days.ToArray())
    {
        xEle.Remove();
    }

The ToArray call will ensure that the entire set of results is returned before you start modifying the XML content. 在开始修改XML内容之前, ToArray调用将确保返回整个结果集。 You can then iterate through the array and delete as many of those items as you like without the loop breaking. 然后,您可以遍历数组,并在不中断循环的情况下删除任意数量的项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM