考虑以下代码段
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
var family = XDocument.Parse("<p><c><g/></c></p>");
var usurper = family.Root.Descendants("g");
family.Root.Element("c").Remove();
family.Root.Add(usurper);
Console.WriteLine(family.ToString());
Console.ReadKey();
}
}
我得到的输出是@"<p />"
,但我想要@"<p><g/></p>"
. 我可以理解它为什么会发生,并且它是正义的,但它不是我需要的输出。
如果我将行的顺序更改为
var usurper = family.Root.Descendants("g");
family.Root.Add(usurper);
family.Root.Element("c").Remove();
建立了循环关系,并且 remove 最终会导致OutOfMemoryException。
有没有一种简单、方便的方法来完成这项工作?
编辑
我实际实施的修复是
var usurper = family.Root.Descendants("g").Single();
family.Root.Element("c").Remove();
family.Root.Add(usurper);
原谅我的脸红。