0

我有这个从 XML 文件加载的结果集

calendarDocument = XDocument.Load(@"C:\CalendarDB.xml");
IEnumerable<XElement> elements = from e in calendarDocument.Root.Elements("Session") select e;

不要说我需要从日历文件中删除一个元素。这行得通吗?

elements.ToList().Remove(someElement);
calendarDocument.Save(@"C:\CalendarDB.xml");

那这个呢?

elements.ToList().Remove(someElement);
elements.Last().AddAfterSelf(anotherElement);
elements.Last().AddAfterSelf(yetAnotherElement);
element.ToList().Remove(anotherElement);
calendarDocument.Save(@"C:\CalendarDB.xml");

我有一种感觉,每次我调用 Last() 时,它都会直接从日历文件中返回一个新的结果集,但是当我调用 Remove() 时,它不会从文件中删除元素,直到我调用 Save() 并且如果我不调用Save() 在每个 Remove() 之后立即调用 Last() 将返回与以前相同的结果集,仍然包含已删除的元素。

有人可以告诉我这是如何工作的吗?我是否需要每次在 Remove() 之后调用 Save() 才能从 Last() 获取最新信息?

4

1 回答 1

0

您不能调用 ToList,它会创建结果集的副本,因此从中删除不会影响原始文档。要从文档中删除元素,只需在元素本身上调用 Remove。例如:

XDocument doc = XDocument.Parse("<root><child>a</child><child>b</child></root>");

IEnumerable<XElement> children = doc.Root.Elements("child");

XElement elementToRemove = children.Last();
elementToRemove.Remove();

XElement newLastElement = children.Last();
Console.WriteLine(newLastElement.Value);

children 变量是可枚举的,它只是一个查询的定义。每次您从它开始查询时,它都会重新启动查询,从而为您提供最新的结果。但你桅杆从孩子开始。

无需以任何方式提交更改,它们会立即应用。只有当您想将修改后的文档写回文件时,您才需要在文档上调用 Save。

于 2012-07-07T06:53:49.457 回答