Jesper Tverskov, July 16, 2008

Remove XML with LINQ to XML in ASP.NET

In ASP.NET we have two main APIs for editing XML: W3C DOM and LINQ to XML. In this tutorial we look at how to remove elements and attributes in LINQ to XML. There are many more properties and methods and ways of achieving the same result than shown below. You must look up the proper documentation for all the details.

Editing XML basically consists of the following: adding, deleting or renaming elements and attributes, and updating content of elements and values of attributes. An API for editing also has properties and methods for comments, processing instructions, etc, but in this tutorial we only look at how to remove elements and attributes.

1. Remove element

I use the following XML document, products.xml, in many of my XML tutorials. How could we delete the product element having an attribute named "id" with a "p3" value?

<?xml version="1.0" encoding="utf-8"?>
  <product id="p1">
  <product id="p3">

To remove an element we simply load the XML document, navigate to the element we want to remove, and remove it. To make it easy to find nodes in the XML document, I prefer to use XPath, "System.Xml.XPath", also when using LINQ to XML.

2. LINQ to XML

2.1 remove-xml-linq.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="remove-xml-linq.aspx.cs" Inherits="remove_xml_linq" %>

2.2 remove-xml-linq.aspx.cs

using System;
using System.Xml.Linq;
using System.Xml.XPath;

public partial class remove_xml_linq : System.Web.UI.Page
  protected void Page_Load(object sender, EventArgs e)
    XDocument xmldoc = XDocument.Load(Server.MapPath("products.xml"));
    xmldoc.XPathSelectElement("products/product[@id = 'p3']").Remove();


    Response.Redirect("products.xml"); // load file in browser

LINQ to XML takes less code than W3C DOM but the nice thing about W3C DOM is that it is a standard API implemented by most programming languages. We can even read or edit an HTML document more or less the same using the HTML version of W3C DOM.

3. Remove attribute

Let us say that we only want to remove the "id" attribute with the "p3" value.

XDocument xmldoc = XDocument.Load(Server.MapPath("products.xml"));
xmldoc.XPathSelectElement("products/product[@id = 'p3']").Attribute("id").Remove();


4. Remove XML in a namespace

See: Read XML with LINQ to XML for how to use XNamespace class.

Updated 2008-08-08