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

Time:01-12

I have an XML like this:

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

And want to have this:

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

Before I used this:

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

Which resulted in:

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

But now I have to preserve the child nodes.

CodePudding user response:

Create a new XElement with the same name (root) and include the nodes of its first element (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);

I you prefer a replace, then replace that first element with its nodes.
Note that this affects the original xml XElement.

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

Console.WriteLine(xml);
  •  Tags:  
  • Related