(C# ASP.NET Core) How to use XML as a database in ASP.NET Core

This is the simplest example of reading and updating a record. For simplicity, the record consists of just one property called Name. An input textbox is used to display the "Name" and the same textbox is used to post the updated value. Reading and writing is done with the built-in XMLSerializer class.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Structure of the Database

Our database will be an XML file containing just one item called <Name> in it.

The XML file will be read and written entirely with the methods of the C# XmlSerializer class. The details of the class can be read on the MSDN documentation here XmlSerializer Class (System.Xml.Serialization)

UI of this Project
(see the linked video for this)

The UI consists of an input textbox with a submit button.

When the form is requested, the OnGet method executes to read the <Name> stored in the XML file.

This string is used to pre-fill the textbox. A user can make any modifications and submit the updated value.

When the OnPost method is processed on the server, the data is written back into the XML file.

Step 1 of 3 - Create an Empty Project
(see the linked video for details)

Create any empty ASP.NET Core project with visual studio. See the linked video for details.

Then add a razor page called Index - you will get two files: Index.cshtml and Index.cshtml.cs. Run your project to ensure that it works so far.

Video Explanation

Please watch the following youtube video:

Step 2 of 3 - Complete the Index.cshtml.cs file
(see the linked video for details)

Dependency injection is used to obtain the reference to IWebHostEnvironment, which is ultimately used to obtain the physical path to the root directory of the application, and consequently to the XML file.

IMPORTANT 1: I have written the model class in the same file [index.cshtml.cs] for the sake of this tutorial only. It is better to use a dedicated "Models" folder for this purpose.

IMPORTANT 2: The second wrong is that the data access code[DAL] has been clubbed in the model class itself. This is not recommended for an actual project. A better approach is to use repository pattern instead.

Write the following code into this file.

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using System.IO;

using System.Xml.Serialization;

namespace Modular.Pages
{

  public class IndexModel : PageModel
  {

    // path to xml file 
    readonly string mPath;

    // dependency injected 
    public IndexModel(IWebHostEnvironment env)
    {

      // path to the database folder 
      mPath = Path.Combine(env.ContentRootPath, "dbFolder");

      // create if not exists 
      if (!Directory.Exists(mPath))
      {

        Directory.CreateDirectory(mPath);

      }

      // now construct the path to xml file 
      mPath = Path.Combine(mPath, "myfile.xml");

    }

    // propert for 2-way binding 
    [BindProperty]
    public MyData mydata { get; set; }

    // handle the get request 
    public void OnGet()
    {

      // see MyData class below 
      mydata = MyData.GetRecord(mPath);

    }

    public void OnPost()
    {

      // see MyData class below 
      MyData.UpdateRecord(mPath, mydata);

    }

  }

  // IndexModel class ends here 

  // MyData model class with helpers 
  // BUT prefer repository pattern 
  public class MyData
  {

    public string Name { get; set; }

    // statics used here only for explaining 
    // the concept, but it is not recommended 
    // use the repository pattern instead 
    public static MyData GetRecord(string file)
    {

      if (!File.Exists(file))
      {

        return new MyData() { Name = string.Empty };

      }

      XmlSerializer ser = new XmlSerializer(typeof(MyData));

      using (Stream stm = new FileStream(file, FileMode.Open, FileAccess.Read))

      {

        return ((MyData)ser.Deserialize(stm));

      }

    }

    public static void UpdateRecord(string file, MyData mydata)
    {

      XmlSerializer ser = new XmlSerializer(typeof(MyData));

      using (Stream stm = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write))

      {

        ser.Serialize(stm, mydata);

      }

    }

  }

  // MyData class ends 
}

Step 3 of 3 - Complete the Index.cshtml file
(see the linked video for details)

This file uses tag helpers for 2-way binding of Name to the input textbox.

@page

@model Modular.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<form method="post">
  Name: <input asp-for="mydata.Name" /> <input type="submit" />
</form>
 

This Blog Post/Article "(C# ASP.NET Core) How to use XML as a database in ASP.NET Core" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.