4

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.

4

2 に答える 2

5

代わりにこれを試してください

var usurper = family.Root.Descendants("g").ToList();

遅延評価のために結果を生成するには、列挙を強制する必要があります。そうしないと、空の結果が得られます。

于 2012-05-15T16:16:11.810 に答える
0

usurper.Remove()ルート要素に追加する前に呼び出す必要があると思います。このステップがなければ、簒奪者は常に「c」要素の子孫になるため、「c」が削除されると、簒奪者も削除されます。

于 2012-05-15T16:21:19.683 に答える