CSharp - Using SetAttributeValue to Add, Delete, and Update Attributes

Introduction

XElement.SetAttributeValue method can add, delete, and update an attribute.

Passing a name that exists with a null value causes the attribute to be deleted.

Demo

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

class Program//from   w w  w . j av  a  2s.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 XAttribute("experience", "first-time"),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby"))));

        Console.WriteLine(System.Environment.NewLine + "Before changing the attributes:");
        Console.WriteLine(xDocument);

        //  This call will update the type attribute's value because an attribute whose
        //  name is "type" exists.
        firstParticipant.SetAttributeValue("type", "beginner");

        //  This call will add an attribute because an attribute with the specified name
        //  does not exist.
        firstParticipant.SetAttributeValue("language", "English");

        //  This call will delete an attribute because an attribute with the specified name
        //  exists, and the passed value is null.
        firstParticipant.SetAttributeValue("experience", null);

        Console.WriteLine(System.Environment.NewLine + "After changing the attributes:");
        Console.WriteLine(xDocument);
    }
}

Result

Related Topic