0

我需要从我的 XML 文件中删除节点中的所有项目,Finished != ""但我的代码仅删除此条件为真的第一项

我的代码:

try
{
    var file = IsolatedStorageFile.GetUserStoreForApplication();
    XElement xElem;

    using (IsolatedStorageFileStream read = file.OpenFile("tasks.xml", FileMode.Open))
    {
        xElem = XElement.Load(read);
    }

    var tasks = from task in xElem.Elements("Task")
                where (string)task.Element("Finished") != ""
                select task;

    using (IsolatedStorageFileStream write = file.CreateFile("tasks.xml"))
    {
        foreach (XElement task in tasks)
        {
            task.Remove();
        }

        xElem.Save(write);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    NavigationService.GoBack();
}

但是如果我用它替换task.Remove();MessageBox会多次显示消息框,因为它是正确的。

我的代码有什么问题?

4

1 回答 1

2

You should call ToList() when you search for items and then use that list as a source in foreach loop, instead of IEnumerable.

var tasks = (from task in xElem.Elements("Task")
             where (string)task.Element("Finished") != ""
             select task).ToList();

It's described on MSDN, within XNode.Remove method description:

In LINQ to XML programming, you should not manipulate or modify a set of nodes while you are querying for nodes in that set. In practical terms, this means that you should not iterate over a set of nodes and remove them. Instead, you should materialize them into a List by using the ToList extension method. Then, you can iterate over the list to remove the nodes. For more information, see Mixed Declarative Code/Imperative Code Bugs (C#) (LINQ to XML).

于 2013-04-03T06:04:25.257 回答