---
title: "How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record."  
description: "How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record."  
author: "Steilla Mitchel"  
published: 2021-11-29  
updated: 2023-08-22  
canonical: https://answers.mindstick.com/qa/94215/how-to-create-xml-file-automatically-when-any-new-record-is-inserted-in-database-in-asp-dot-net-mvc-also-delete-and-update-that-xml-file-base-on-record  
category: "asp.net"  
tags: ["asp.net mvc", "asp.net"]  
reading_time: 16 minutes  

---

# How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.

How to create [XML file](https://www.mindstick.com/forum/360/how-to-read-xml-file-in-php) automatically when any new record is inserted in [database in Asp.net](https://www.mindstick.com/forum/158707/what-are-the-different-methods-available-for-connecting-to-a-database-in-asp-dot-net-mvc) [MVC](https://www.mindstick.com/articles/23249/rdlc-report-in-mvc-application)? Also [delete](https://www.mindstick.com/forum/159778/what-is-the-delete-statement-in-sql-and-how-is-it-used-to-remove-data-from-a-table) and [Update](https://www.mindstick.com/forum/156355/what-is-google-pigeon-update) that XML file when Record is delete or update.

## Answers

### Answer by user

**[Asp.net MVC](https://www.mindstick.com/articles/1580/ajax-with-asp-dot-net-mvc) code for create, update and delete automatically [Xml](https://www.mindstick.com/articles/178/xml-control-in-asp-dot-net) [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) from folder based on Record.** Sometimes we need to create automatically xml file of every new when insert into [database](https://www.mindstick.com/articles/100/windows-service-to-update-record-from-one-database-to-another-after-certain-interval-of-time). After create xml file of every record we want to update them automatically when any user update his/her record from webpage and also delete Xml file automatically when any record is deleted from page. Lets start, all process performed in Visual Studio with SQL Sercer database connectivity. Asp.net MVC code for create Xml file when any new record is inserted. View Page code,

```
@model DemoXMLXML.Models.StudentRecordDetails
@{
    ViewBag.Title = 'Student';
}
@using (Html.BeginForm('AddStudent', 'Student', FormMethod.Post))
{
<div class='container'>
    <div class='form-group'>
        <label>stuID</label>
        @if (Model != null && Model.stuID>0)
        {
            @Html.TextBoxFor(x => x.stuID, new { @class = 'form-control', @readonly = 'readonly' })
        }
        else
        {
            @Html.TextBoxFor(x => x.stuID, new { @class = 'form-control' })
        }
    </div>
    <div class='form-group'>
        <label>stuName</label>
        @Html.TextBoxFor(x => x.stuName, new { @class = 'form-control' })
    </div>
    <div class='form-group'>
        <label>stuCourse</label>
        @Html.TextBoxFor(x => x.stuCourse, new { @class = 'form-control' })
    </div>
    <div class='form-group'>
        <label>stuAge</label>
        @Html.TextBoxFor(x => x.stuAge, new { @class = 'form-control' })
    </div>
    <div class='form-group'>
        <label>Marks</label>
        @Html.TextBoxFor(x => x.stuMarks, new { @class = 'form-control' })
    </div>
    <div class='from-group'>
        <button type='submit' class='btn btn-primary'>Submit</button>
    </div>
</div>
}
```

The page look like as follow, \
![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/44da5f97-b1aa-42d4-aaa0-ee4fc3294985.png) \
**Model page code of this page,**

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DemoXMLXML.Models
{
    [MetadataType(typeof(StudentRecordDetails))]
    public partial class StudentRecord
    {
    }
    public  class StudentRecordDetails
    {
        [Required(ErrorMessage = 'Requered')]
        public int stuID { get; set; }
        [Required(ErrorMessage = 'Requered')]
        public string stuName { get; set; }
        [Required(ErrorMessage = 'Requered')]
        public string stuCourse { get; set; }
        [Required(ErrorMessage = 'Requered')]
        public Nullable<int> stuAge { get; set; }
        [Required(ErrorMessage = 'Requered')]
        public Nullable<int> stuMarks { get; set; }
    }
}
Controller page code,
Asp.net MVC code for creating automatically xml file,
//Creating new xml file of every new users
        private void CreateXml()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration('1.0', 'UTF-8', null);
            doc.AppendChild(docNode);
            XmlElement studentDataNode = doc.CreateElement('StudentData');
            (studentDataNode).SetAttribute('xmlns:xsd', 'https://www.mindstick.com');
            doc.AppendChild(studentDataNode);
            XmlNode StudentRecords = doc.CreateElement('StudentRecords');
            studentDataNode.AppendChild(StudentRecords);
            XmlNode StudentRecord = doc.CreateElement('Record');
            StudentRecords.AppendChild(StudentRecord);
            XmlNode StudentName = doc.CreateElement('StudentName');
            StudentName.AppendChild(doc.CreateTextNode(stu.stuName));
            StudentRecord.AppendChild(StudentName);
            XmlNode StudentType = doc.CreateElement('StudentType');
            StudentType.AppendChild(doc.CreateTextNode(stu.stuCourse));
            StudentRecord.AppendChild(StudentType);
            XmlNode studentAge = doc.CreateElement('StudentAge');
            studentAge.AppendChild(doc.CreateTextNode(stu.stuAge.ToString()));
            StudentRecord.AppendChild(studentAge);
            XmlNode studentMarks = doc.CreateElement('StudentMarks');
            studentMarks.AppendChild(doc.CreateTextNode(stu.stuMarks.ToString()));
            StudentRecord.AppendChild(studentMarks);
            //location of folder where xml file save.
            var basepath = Path.Combine(Environment.CurrentDirectory, @'C:\Verma\C# Folder\XML Files');
            // if folder is not exists then create
            if (!Directory.Exists(basepath))
            {
                Directory.CreateDirectory(basepath);
            }
            //create every xml file name by student id with .xml extension
            var newFile = string.Format('{0}{1}', stu.stuID.ToString(), '.xml');
            string fileName = basepath + '\\' + newFile;
            //save xml file
            doc.Save(fileName);
        }
```

**Add new record in database table StudentRecords,**

```
public ActionResult AddStudent(StudentRecordDetails model)
        {
             stu = new StudentRecord();
            stu.stuID = model.stuID;
            stu.stuName = model.stuName;
            stu.stuCourse = model.stuCourse;
            stu.stuAge = model.stuAge;
            stu.stuMarks = model.stuMarks;
            using (_db = new MyCollegeDbEntities())
            {
                    //insert new record into database
                    _db.StudentRecords.Add(stu);
                    _db.SaveChanges();
                    CreateXml();
                }
    }
```

If any user’s data is already exist in database and want to update record/data then xml file also will update as well as database table is update.

```
public ActionResult AddStudent(StudentRecordDetails model)
        {
             stu = new StudentRecord();
            stu.stuID = model.stuID;
            stu.stuName = model.stuName;
            stu.stuCourse = model.stuCourse;
            stu.stuAge = model.stuAge;
            stu.stuMarks = model.stuMarks;
            using (_db = new MyCollegeDbEntities())
            {
                StudentRecord data = _db.StudentRecords.Where(x => x.stuID == stu.stuID).SingleOrDefault();
                if(data == null)
                {
                    //insert new record into database
                    _db.StudentRecords.Add(stu);
                    _db.SaveChanges();
                    CreateXml();
                }
                //update if records is already exists in database.
                else
                {
                    //udate record when user want to update data.
                    data.stuName = stu.stuName;
                    data.stuCourse = stu.stuCourse;
                    data.stuAge = stu.stuAge;
                    data.stuMarks = stu.stuMarks;
                    //xml file with its location
                    string path = @'C:\Verma\C# Folder\XML Files\'+Convert.ToString(data.stuID)+'.xml';
                    //if particulat xml file is exists in folder then update
                    if (System.IO.File.Exists(path))
                    {
                          XmlDocument doc = new XmlDocument();
                        //Load file in Xml document
                        doc.Load(path);
                        //select xml node(tags) where student name
                        XmlNode nodeName = doc.SelectSingleNode('/StudentData/StudentRecords/Record/StudentName');
                       //update name
                        nodeName.InnerText=data.stuName;
                        //select xml node(tags) where student Course
                        XmlNode nodeCourse = doc.SelectSingleNode('/StudentData/StudentRecords/Record/StudentType');
                        //update CourseName
                        nodeCourse.InnerText = data.stuCourse;
                        //select xml node(tags) where student Age
                        XmlNode nodeAge = doc.SelectSingleNode('/StudentData/StudentRecords/Record/StudentAge');
                        //update Age
                        nodeAge.InnerText = data.stuAge.ToString();
                        //select xml node(tags) where student Marks
                        XmlNode nodeMarks = doc.SelectSingleNode('/StudentData/StudentRecords/Record/StudentMarks');
                        //update Marks
                        nodeMarks.InnerText = data.stuMarks.ToString();
                        doc.Save(path);
                        _db.SaveChanges();                    }
                }
            }
            return View('Student');
        }
```

Now we have create a list of all student record and show it in a view page,

```
public ActionResult StudentList()
        {
            using (var db = new MyCollegeDbEntities())
            {
                //create a list of student record from database table
                List<StudentRecord> collection = db.StudentRecords.AsEnumerable<StudentRecord>().ToList();
                ViewBag.data = collection;
            }
            return View();
        }
```

View page source code is as, here all records is added one by one in list from database table.

```
@{
    ViewBag.Title = 'StudentList';
}
<table border='1' class='table table-hover'>
    <tr>
        <th>ID</th>
        <th>stuName</th>
        <th>stuCource</th>
        <th>stuAge</th>
        <th>stuMarks</th>
        <th>Action</th>
    </tr>
    @{
        foreach (var item in @ViewBag.data)
        {
        <tr>
            <td>@item.stuID</td>
            <td>@item.stuName</td>
            <td>@item.stuCourse</td>
            <td>@item.stuAge</td>
            <td>@item.stuMarks</td>
            <td>
                <a href='@Url.Action('Student', new { item.stuID,item.stuName,item.stuCourse,item.stuAge, item.stuMarks})' class='btn btn-success'>Edit</a>
                <a href='@Url.Action('Delete', new { item.stuID})' class='btn btn-danger'>Delete</a>
            </td>
        </tr>
        }
    }
</table>
```

![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/ec1dc493-b29e-404a-bd4e-209fd12a0de0.png) When you want to update any record by clicking in Edit button then it returns on same view page where new record is inserted, suppose I want to update a record which ID is 403, ![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/a6732ee1-b257-42e8-811e-475aa3a036b6.png) In this above case ID is not editable it can read only. Here xml file also update if you give submit with any changes in record anywhere. When above record is add then its xml file is automatically created, ![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/f621f6ea-6799-45a3-831d-3a571869cf11.png)\
And if you want to update in the above record the above xml file also will update automatically, Here some changes in above record, suppose edit the stuName and stuCourse like following and submit them, ![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/feb5bbdf-7a92-4747-9d9a-c148d7ceb532.png) Its xml file also will update automatically, ![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/82c0a7dd-f070-4e92-9e64-2d96e5903902.png) Now if any record is Deleted the xml file will also being delete automatically.

```
public ActionResult Delete(int stuID)
        {
            using (var db = new MyCollegeDbEntities())
            {
                var result = db.StudentRecords.Where(x => x.stuID == stuID).FirstOrDefault();
                //xml file path
                string path = @'C:\Verma\C# Folder\XML Files\';
                //xml file name
                string file = stuID + '.xml'.ToString();
                if (System.IO.File.Exists(Path.Combine(path, file)))
                {
                    // if exist xml file then delete.
                    System.IO.File.Delete(Path.Combine(path,file));
                }
                db.StudentRecords.Remove(result);
                db.SaveChanges();
                List<StudentRecord> collect = db.StudentRecords.AsEnumerable<StudentRecord>().ToList();
                ViewBag.data = collect;
                return View('StudentList', collect);
            }
```

![How to create XML file automatically when any new record is inserted in database in Asp.net MVC? Also delete and Update that XML file base on Record.](https://answers.mindstick.com/questionanswer/fd0288b9-659f-4bfc-b82c-6c692dd8e04b/images/bbec1e12-d284-4acc-a88c-0d384afccee8.png)\
\

### Answer by Kshitij Agrawal

To create **XML** file automatically need to follow some steps:

1. First **Setup the Database:**

setting up the database is necessary. make sure the database you setting up is properly configured.

## 2. Create a model

In the **[ASP.NET](https://www.mindstick.com/articles/257/ajax-toolkit-calendarextender-control-in-asp-dot-net)** MVC application, create a model that represents the data structure of the database table.

**3. Database Operations.**

Now implement the database operations like insert, delete, update using entity framework which will involves in creating, deleting and updating the records in database.

## 4. XML Operations

Now for each database operations, will need to perform XML operations as name shows. Use the **‘System.Xml’** namespace in C# to work with XML data.

1. **Create XML File:** When a new record is inserted into the database, you'll create a new XML file and populate it with data from the newly inserted database record. You can use the **XmlDocument** class to create and manipulate XML data.
2. **Update XML File:** When a record is updated in the database, you need to locate the corresponding XML file (e.g., based on a unique identifier) and update the data in the XML file to match the updated database record. Load the XML, make the necessary changes, and save it back.

For deleting and Updating that XML file base on Record.

## Update XML File on Record Update:

When a record is updated in the database, you can locate the corresponding XML file (based on a unique identifier, such as the record's primary key), update the data in the XML file to match the updated database record, and save the XML file.**Update XML File on Record Update:** Need to do some codings.

// Assuming you have the updated record available in the 'updatedRecord' variable\
// Load the XML file\
XmlDocument xmlDoc = new XmlDocument();\
xmlDoc.Load("path/to/your/xmlfile.xml");

// Find the node to update (based on some identifier)\
XmlNode nodeToUpdate = xmlDoc.SelectSingleNode("/root/node[@id='1']");

// Update the node's data\
nodeToUpdate["Name"].InnerText = updatedRecord.Name;\
// Update other data as needed

// Save the updated XML\
xmlDoc.Save("path/to/your/xmlfile.xml");\

## Delete XML File on Record Deletion:

When a record is deleted from the database, locate the corresponding XML file and delete it. Here's how you can delete an XML file in C#:

// Assuming you have the ID of the record to delete\
int recordIdToDelete = 1; // Replace with the actual ID\
string xmlFilePathToDelete = $"path/to/your/xmlfile_{recordIdToDelete}.xml";

if (System.IO.File.Exists(xmlFilePathToDelete))\
{\
System.IO.File.Delete(xmlFilePathToDelete);\
}\

## Handle Errors and Edge Cases:

Just like with the insert operation, be sure to handle errors and edge cases when updating and deleting XML files. This includes scenarios where the XML file does not exist or if there are issues with the XML file manipulation.

## Testing:

Thoroughly test your code to ensure that XML files are correctly updated when records are updated in the database and deleted when records are deleted.

## Consider Using a Unique Identifier:

To ensure that you can easily locate the corresponding XML file for each record, consider using a unique identifier (e.g., the record's primary key) as part of the XML file's name or content. This will make it easier to match database records with XML files.


---

Original Source: https://answers.mindstick.com/qa/94215/how-to-create-xml-file-automatically-when-any-new-record-is-inserted-in-database-in-asp-dot-net-mvc-also-delete-and-update-that-xml-file-base-on-record

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
