CSharp - LINQ XML Remove

Introduction

The Remove operator operates on a sequence of nodes or attributes to remove them.

Prototypes

The Remove operator has two prototypes. The First Remove Prototype

public static void Remove (
        this IEnumerable<XAttribute> source
      )

The Second Remove Prototype

public static void Remove<T> (
        this IEnumerable<T> source
      ) where T : XNode

This version is called on a sequence of a specified type.

Demo

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

class Program/*from  w  w  w. j  ava  2s .  com*/
{
    static void Main(string[] args){
              XDocument xDocument = new XDocument(
                new XElement("Books",
                  new XElement("Book",
                    new XAttribute("type", "Author"),
              new XComment("This is a new author."),
              new XElement("FirstName", "Joe"),
              new XElement("LastName", "Ruby")),
            new XElement("Book",
              new XAttribute("type", "Editor"),
              new XElement("FirstName", "PHP"),
              new XElement("LastName", "Python"))));
        
        IEnumerable<XAttribute> attributes =
          xDocument.Element("Books").Elements("Book").Attributes();
        
        //  First, we will display the source attributes.
        foreach (XAttribute attribute in attributes)
        {
          Console.WriteLine("Source attribute: {0} : value = {1}",
            attribute.Name, attribute.Value);
        }
        
        attributes.Remove();
        
        //  Now, we will display the XML document.
        Console.WriteLine(xDocument);
    }
}

Result

Related Topics