Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将节点临时添加到XDocument_C#_Linq To Xml - Fatal编程技术网

C# 将节点临时添加到XDocument

C# 将节点临时添加到XDocument,c#,linq-to-xml,C#,Linq To Xml,我需要为XDocument创建一个临时根节点,但我需要在不破坏引用的情况下这样做 因此,该方法应该仍然有效 XElement x = doc.Root.FirstNode; // Inset magic here that adds the "MyTempRoot" Console.WriteLine(x.Name); // This should still work 范例 <elements> <item /> <item />

我需要为XDocument创建一个临时根节点,但我需要在不破坏引用的情况下这样做

因此,该方法应该仍然有效

XElement x = doc.Root.FirstNode;
// Inset magic here that adds the "MyTempRoot"
Console.WriteLine(x.Name); // This should still work
范例

<elements>
    <item />
    <item />
    <item />
</elements>


想出了一个办法

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);
    }
}

以下内容就足够了

doc.Root.ReplaceWith(new XElement("MyTempRoot", doc.Root));

如果要使用同一对象,唯一的方法是添加临时节点,然后将其删除。或者,复制对象。请注意,以这种方式复制元素会丢失XML注释;不确定它是否适用于这里,但可能值得一提。
doc.Root.ReplaceWith(new XElement("MyTempRoot", doc.Root));