我知道如何做第一部分(我假设您可以使用 LINQ(即拥有 .NET 3.5 或更高版本),这只是使用一些 XLINQ 并连接 2 个事件 Changed/Changed 的问题,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
namespace ConsoleApplication1
{
class Program
{
public static XDocument doc;
static void Main(string[] args)
{
doc = XDocument.Parse("<books><book>Gone with the wind</book></books>");
doc.Changed += Doc_Changed;
doc.Changing += Doc_Changing;
PrintResults();
XElement newElement = new XElement("book", "Treasure Island");
doc.Elements().First().Add(newElement);
newElement.Remove(); //remove this noe from parent
Console.ReadLine();
}
static void Doc_Changing(object sender, XObjectChangeEventArgs e)
{
PrintChangeResults(e);
}
static void Doc_Changed(object sender, XObjectChangeEventArgs e)
{
PrintChangeResults(e);
}
public static void PrintChangeResults(XObjectChangeEventArgs e)
{
Console.WriteLine(string.Format("Change was {0}, Document now has {1} elements",
e.ObjectChange, doc.Elements().First().Elements().Count()));
}
public static void PrintResults()
{
Console.WriteLine(string.Format("Document now has {0} elements",
doc.Elements().First().Elements().Count()));
}
}
}
这将导致类似以下输出
文档现在有 1 个元素 更改为添加,文档现在有 1 个元素 更改为添加,文档现在有 2 个元素 更改为移除,文档现在有 2 个元素 更改为移除,文档现在有 1 个元素
所以这应该让你有 1/2 的方式(前提是你可以使用 LINQ)