1

I have XML Document like

 <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.

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.

3
  • 1
    Add some debugging. What IS returned by your Linq? Commented Apr 7, 2014 at 11:19
  • I don't actually see anything wrong with this code, it's working just fine for me. Please describe why you think that ti's not working. Commented Apr 7, 2014 at 11:36
  • If you're testing for (DateTime)nm.Element("Date") >= DateTime.Now.AddDays(-30), then you don't also need to test for (DateTime)nm.Element("Date") <= DateTime.Now. Commented Apr 7, 2014 at 11:51

1 Answer 1

2

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. You can then iterate through the array and delete as many of those items as you like without the loop breaking.

Sign up to request clarification or add additional context in comments.

4 Comments

What you said makes sense, but I can actually get the correct result without that...so I'm not sure if that's actually necessary in this case.
Are you sure value30days isn't already a new enumerable collection, separate from the original XElement?
I was using LINQPad to test though, so maybe LINQPad is actually doing something extra like calling ToArray() for me?
I tested in LinqPad as well, using the XML above as a base. When I added one item to remove, it removed that one item. When I added several items to remove it only took one of them away. Adding ToArray to the foreach resulted in all of the items being removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.