Micwill Aragon
Micwill Aragon

Reputation: 9

How to replace element of xml using xdocument in c#

example xml:

<string-name>
    <given-name>Sisgon</given-name>
</string-name>

changes of xml element:

<string-name>
    <surname>Sisgon</surname>
</string-name>

I want to change the given-name tag to surname without changing the inner text.

Upvotes: 0

Views: 1431

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26342

How about this

XDocument xmlDoc = XDocument.Parse(content);
var event_nodes = xmlDoc.Descendants("given-name");
foreach(var node in event_nodes)
{
    node.Name = "surname";
}
System.Diagnostics.Debug.WriteLine(xmlDoc.ToString());

To add an attribute add the following in the for each:

XAttribute attribute = new XAttribute("Name","value");
node.Add(attribute)

Upvotes: 1

Related Questions