CSharp - Using SetElementValue to Update, Add, and Delete Child Elements

Introduction

SetElementValue method will only affect the first child element it finds with the specified name.

Any subsequent elements with the same name will not be affected.

Demo

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

class Program//  w w w  .  j av  a  2 s .com
{
    static void Main(string[] args){
        //  we will use this to store a reference to one of the elements in the XML tree.
        XElement firstParticipant;
        
        XDocument xDocument = new XDocument(
          new XElement("Books", firstParticipant =
            new XElement("Book",
              new XAttribute("type", "Author"),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby"))));
        
        Console.WriteLine(System.Environment.NewLine + "Before updating elements:");
        Console.WriteLine(xDocument);
        
        //  First, we will use XElement.SetElementValue to update the value of an element.
        //  Since an element named FirstName is there, its value will be updated to Joseph.
        
              firstParticipant.SetElementValue("FirstName", "Joseph");
        
              //  Second, we will use XElement.SetElementValue to add an element.
              //  Since no element named MiddleInitial exists, one will be added.
              firstParticipant.SetElementValue("MiddleInitial", "C");
        
              //  Third, we will use XElement.SetElementValue to remove an element.
              //  Setting an element's value to null will remove it.
              firstParticipant.SetElementValue("LastName", null);
        
              Console.WriteLine(System.Environment.NewLine + "After updating elements:");
              Console.WriteLine(xDocument);
    }
}

Result

Related Topic