如何在保留其值和子节点的同时删除节点?

How to remove a node while preserving its value and child nodes?

我有一个 XML 这样的:

<root>
<parent1>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</parent1>
</root>

并且想要这个:

<root>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</root>

在我使用之前:

foreach (var p in doc.Descendants("parent1"))
    p.ReplaceWith(p.Value);

结果是:

<root>Some random text here. And a random image here.</root>

但现在我必须保留子节点。

创建一个新的同名 XElement (root) 并包含其第一个元素 (parent) 的节点。

const string Xml = @"
    <root>
        <parent1>Some random <child1>text </child1>here. And a random <child2>image </child2>here.</parent1>
    </root>";
var xml = XElement.Parse(Xml);

var result = new XElement(
    xml.Name,
    xml.Elements().First().Nodes()
    );

Console.WriteLine(result);

如果您更喜欢替换,请将第一个元素替换为其节点。
请注意,这会影响原始 xml XElement.

var first = xml.Elements().First();
first.ReplaceWith(first.Nodes());

Console.WriteLine(xml);