简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM