Consider the following snippet
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();
}
}
The output I get is @"<p />"
but I would like @"<p><g/></p>"
. I can see why it happens and, there is a justice to it but, its not the output I need.
If I change the the order of the lines to
var usurper = family.Root.Descendants("g");
family.Root.Add(usurper);
family.Root.Element("c").Remove();
a circular relationship is set up and the remove eventualy causes an OutOfMemoryException.
Is there a simple, expedient way to make this work?
EDIT
The fix I actually implemented was
var usurper = family.Root.Descendants("g").Single();
family.Root.Element("c").Remove();
family.Root.Add(usurper);
Excuse my blushes.