The following should be sufficient
doc.Root.ReplaceWith(new XElement("MyTempRoot", doc.Root));
質問
I need to create a temporary root node for an XDocument, but i need to do this without destroying the reference.
So the should still work
XElement x = doc.Root.FirstNode;
// Inset magic here that adds the "MyTempRoot"
Console.WriteLine(x.Name); // This should still work
Example
<elements>
<item />
<item />
<item />
</elements>
To
<MyTempRoot>
<elements>
<item />
<item />
<item />
</elements>
</MyTempRoot>
解決
The following should be sufficient
doc.Root.ReplaceWith(new XElement("MyTempRoot", doc.Root));
他のヒント
Figured out a way
private void AddTempRoot(XDocument doc)
{
XElement tempRoot= new XElement("MyTempRood");
var elements = doc.Elements();
foreach (var element in elements)
{
element.Remove();
tempRoot.Add(element);
}
doc.Add(tempRoot);
}
private void RemoveTempRoot(XDocument doc)
{
var tempRoot = doc.Root;
tempRoot.Remove();
var elements = tempRoot.Elements();
foreach (var element in elements)
{
element.Remove();
doc.Add(element);
}
}