In this article, I will demonstrate how to import XML data into SQL server using MVC 5 and entity framework. I will create a XML file and upload it into FileUpload in project. I will also use jQuery datatable plugging for searching, shorting and paging.
- CREATE TABLE [dbo].[Product](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Price] [decimal](18, 0) NULL,
- [Quantity] [int] NULL,
- CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Step 2
Open Visual Studio 2015, click on New Project, and create an empty web application project.
Screenshot for creating new project 1
After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project, and then click on OK as shown in below screenshot.
Screenshot for creating new project 2
After clicking on OK one more window will appear; choose empty, check on MVC checkbox and click on OK as shown below screenshot.
Screenshot for creating new project 3
After clicking on OK, the project will be created with the name of MvcImportXMLData_Demo.
Step 3
Add Entity Framework now. For that, right click on Models folder, select Add, then select New Item, then click on it.
Screenshot for adding entity framework 1
After clicking on new item, you will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name DBModels (this name is not mandatory you can give any name) and click on Add.
Screenshot for adding entity framework 2
After you click on "Add a window", the wizard will open, choose EF Designer from database and click Next.
Screenshot for adding entity framework 3
After clicking on Next a window will appear. Choose New Connection. Another window will appear, add your server name if it is local then enter dot (.). Choose your database and click on OK.
Screenshot for adding entity framework 4
Connection will be added. Save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.
Screenshot for adding entity framework 5
After clicking on NEXT another window will appear choose database table name as shown in the below screenshot then click on Finish.
Screenshot for adding entity framework 6
Screenshot for adding entity framework-7
Entity framework will be added and respective class gets generated under Models folder.
Screenshot for adding entity framework 8
Following class will be added,
- namespace MvcImportXMLData_Demo.Models
- {
- using System;
- using System.Collections.Generic;
-
- public partial class Product
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public Nullable<decimal> Price { get; set; }
- public Nullable<int> Quantity { get; set; }
- }
- }
Step 4
Create a class in Models Folder name it ProductMetaData.cs
Screenshot-1
Screenshot-2
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- using System.Xml.Serialization;
- namespace MvcImportXMLData_Demo.Models
- {
- [Serializable]
- [XmlRoot("product")]
- public class ProductMetaData
- {
- [XmlElement("id")]
- public int Id { get; set; }
-
- [XmlElement("name")]
- public string Name { get; set; }
-
- [XmlElement("price")]
- public Nullable<decimal> Price { get; set; }
-
- [XmlElement("quantity")]
- public Nullable<int> Quantity { get; set; }
- }
-
- [MetadataType(typeof(ProductMetaData))]
- public partial class Product
- {
- }
- }
Step 5
Right click on Controllers folder, select Add, then choose Controller as shown in the below screenshot.
After clicking on controller a window will appear choose MVC5 Controller-Empty click on Add.
After clicking on Add another window will appear with DefaultController. Change the name to HomeController then click on Add. HomeController will be added under Controllers folder. Remember don’t change the Controller suffix for all controllers, change only highlight, and instead of Default just change Home as shown in the below screenshot.
Complete code for controller
- using MvcImportXMLData_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Xml.Linq;
-
- namespace MvcImportXMLData_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult GetData()
- {
- using (DBModel db = new DBModel())
- {
- List<Product> employeeList = db.Products.ToList<Product>();
- return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
- }
- }
-
- [HttpPost]
- public ActionResult Upload(HttpPostedFileBase xmlFile)
- {
- if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
- {
- var xmlPath = Server.MapPath("~/FileUpload" + xmlFile.FileName);
- xmlFile.SaveAs(xmlPath);
- XDocument xDoc = XDocument.Load(xmlPath);
- List<Product> productList = xDoc.Descendants("product").Select
- (product => new Product
- {
- Id = Convert.ToInt32(product.Element("id").Value),
- Name = product.Element("name").Value,
- Price = Convert.ToDecimal(product.Element("price").Value),
- Quantity = Convert.ToInt32(product.Element("quantity").Value)
- }).ToList();
-
- using (DBModel db = new DBModel())
- {
- foreach (var i in productList)
- {
- var v = db.Products.Where(a => a.Id.Equals(i.Id)).FirstOrDefault();
-
- if (v != null)
- {
- v.Id = i.Id;
- v.Name = i.Name;
- v.Price = i.Price;
- v.Quantity = i.Quantity;
- }
- else
- {
- db.Products.Add(i);
- }
- db.SaveChanges();
- }
- }
- ViewBag.Success = "File uploaded successfully..";
- }
- else
- {
- ViewBag.Error = "Invalid file(Upload xml file only)";
- }
- return View("Index");
- }
- }
- }
Step 6
Create a folder to upload file with name FileUpload.
Step 7
Right click on index action method in controller. Add view window will appear with default index name unchecked (use a Layout page), and click on Add as shown in the below screenshot. View will be added in views folder under Home folder with name index.
Screenshot for adding view
Step 8
Design view with HTML, cshtml and bootstrap 4 classes,
Complete index view code
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <link href="~/Content/dataTables.bootstrap4.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery.dataTables.min.js"></script>
- <script src="~/scripts/dataTables.bootstrap4.min.js"></script>
- <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"></script>
- <style type="text/css">
- .error {
- color: red;
- display: inline-block;
- margin-bottom: -57px !important;
- width: 100%;
- }
- </style>
- <script type="text/javascript">
- $(document).ready(function () {
- $('form').validate({
- rules: {
- xmlFile: {
- required: true
- }
- },
- messages: {
- xmlFile: "Choose file to upload",
- }
- })
- $('#dataTable').DataTable({
- "ajax": {
- "url": "/Home/GetData",
- "type": "GET",
- "datatype": "json"
- },
- "columns": [
- { "data": "Id" },
- { "data": "Name" },
- { "data": "Price" },
- { "data": "Quantity" }
- ]
- });
- });
- </script>
- </head>
- <body>
- <div class="container py-5">
- @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- <div class="row">
- <div class="col-sm-1 col-md-6 col-xs-12">
- <h5 class="text-danger">@ViewBag.Error</h5>
- <h5 class="text-success">@ViewBag.Success</h5>
- <div class="form-group">
- <label>Choose XML File:</label>
- <div class="input-group">
- <div class="custom-file">
- <input id="xmlFile" name="xmlFile" type="file" class="custom-file-input" />
- <label class="custom-file-label"></label>
- </div>
- <div class="input-group-append">
- <input type="submit" class="btn btn-outline-primary" value="Upload" />
- </div>
- </div>
- </div>
- </div>
- </div>
- }
- <table id="dataTable" class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Price</th>
- <th>Quantity</th>
- </tr>
- </thead>
- </table>
- </div>
- </body>
- </html>
Step 9
Create an xml file with the name products.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <products>
- <product>
- <id>1</id>
- <name>Mobele Phone</name>
- <price>12000</price>
- <quantity>2</quantity>
- </product>
- <product>
- <id>2</id>
- <name>Hand Watch</name>
- <price>1200</price>
- <quantity>5</quantity>
- </product>
- <product>
- <id>3</id>
- <name>T-Shirt</name>
- <price>499</price>
- <quantity>2</quantity>
- </product>
- <product>
- <id>4</id>
- <name>Shoe</name>
- <price>999</price>
- <quantity>2</quantity>
- </product>
- <product>
- <id>5</id>
- <name>Jeans</name>
- <price>999</price>
- <quantity>2</quantity>
- </product>
- </products>
Step 10
Run Project ctrl+F5
Screenshot-1
Screenshot-4
Screenshot-5
Screenshot-6
Conclusion
In this article I have explained how to import xml Meta data in SQL server using MVC 5 step by step. I hope it will help you in your project.