Tuesday, 29 April 2014

C#.NET - How to delete XML Node from XML file step by step

In this article you will get to know how to delete an Xml Node from the Xml Document.

We have an XmlDocument class in System.Xml namespace. With the help of XmlDocument class data members and member functions we can delete node from the Xml Document.

To delete an Xml node from the Xml Document go through the following step by step procedure.

1. First create an Xml File with some sample employees as follows.


Xml File

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  
  <Employee>
    <ID>SE01</ID>
    <Name>Srinubabu</Name>
    <Address>Hyderabad</Address>   
  </Employee>

  <Employee>
    <ID>SE02</ID>
    <Name>Gajendra</Name>
    <Address>Pune</Address>
  </Employee>

  <Employee>
    <ID>SE03</ID>
    <Name>Prafulla</Name>
    <Address>Gurgon</Address>
  </Employee>

  <Employee>
    <ID>SE02</ID>
    <Name>Satheesh</Name>
    <Address>Chennai</Address>
  </Employee>
  
</Employees>

2. Create a new website in Visual Studio.

3. Add an aspx page "Delete-node-from-xml.aspx" to the website and write the following code.

Note: Please go through the code and comments in the following code you will easily understand the process of deleting the node from Xml Document.



Delete-node-from-xml.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Delete-node-from-xml.aspx.cs"
    Inherits="Delete_node_from_xml" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
    Employee ID:
    <asp:TextBox ID="txtEmployeeID" runat="server" />
    <asp:Button ID="btnDeleteEmployee" Text="Delete Employee" runat="server" OnClick="btnDeleteEmployee_Click" /><br />
    <br />
    <asp:Label ID="lblStatus" ForeColor="Red" Font-Size="13" Text="" runat="server" />
    </form>
</body>
</html>

Delete-node-from-xml.aspx.cs

using System;
using System.Xml;

public partial class Delete_node_from_xml : System.Web.UI.Page
{
   
    protected void btnDeleteEmployee_Click(object sender, EventArgs e)
    {
        var filePath = @"C:\Users\manduvalkuritis\Desktop\Srinubabu\XMLManipulations\Employees.xml";
        DeleteEmployeeByEmployeeID(filePath, txtEmployeeID.Text.Trim());
    }

    private void DeleteEmployeeByEmployeeID(string xmlFilePath, string employeeID)
    {
        // Initialize a new instance of the XmlDocument.
        var xdoc = new XmlDocument();
        xdoc.Load(xmlFilePath);

        // Get the root XmlElement of the document.
        XmlNode rootNode = xdoc.DocumentElement;

        // Select a list of Xml nodes matching with employee ID
        XmlNodeList nodes = rootNode.SelectNodes("Employee");

        bool isEmployeeFound = false;

        // Go throug each and every element 
        foreach (XmlNode item in nodes)
        {
            // Find the Xml node with the given employee ID
            if (item.SelectSingleNode("ID").InnerText == employeeID)
            {
                isEmployeeFound = true;

                // Delete the employee node from the xml document.;
                rootNode.RemoveChild(item);
            }
        }

        if (isEmployeeFound)
        {
            lblStatus.Text = "Emloyee Deleted Successfully.";
        }
        else
        {
            lblStatus.Text = "Emloyee doesn't found please enter correct employee id.";
        }

        // Finally save the xml file.
        xdoc.Save(xmlFilePath);
    }
}


4. Now run the page in browser the output of the page looks as follows.



5. Enter an invalid employee id which was not available in Xml Document and then click on delete button. It will show the error message as follows.



6. Now enter a valid employee id and click on delete button. Now an employee node will be delete from the xml document.



7. Now open the Xml file and observe an employee node with the id "". The employee node with the employee id "" deleted from the Xml file.


Xml File

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  
  <Employee>
    <ID>SE02</ID>
    <Name>Gajendra</Name>
    <Address>Pune</Address>
  </Employee>
  
  <Employee>
    <ID>SE03</ID>
    <Name>Prafulla</Name>
    <Address>Gurgon</Address>
  </Employee>
  
  <Employee>
    <ID>SE02</ID>
    <Name>Satheesh</Name>
    <Address>Chennai</Address>
  </Employee>
  
</Employees>

So, In this way we can delete a node from the Xml Document.

Thank you....

No comments: