In this article i will show you how you can read or parse XML file and display xml file data table or tabular format in your asp.net core 6/MVC application using c#.net.
Other Articles: Asp.Net Core 6 : Rename / Change File or Image Name and Upload in wwwroot Using C#.Net, File Upload in Folder (Folder Outside wwwroot) Asp.Net Core 6 / MVC Using C#, Access Connection String In Asp.Net Core 6 Controller From appsettings.json C#, How to get value from XML using Linq in C#.
Now for this article we will create a new asp.net core 6 application and add and XML file in your xml file folder and add your xml file detail.
<?xml version="1.0" encoding="utf-8" ?> <students>
<student>
<rollno>1</rollno>
<name>Student Name 1</name>
</student>
<student>
<rollno>2</rollno>
<name>Student Name 2</name>
</student>
<student>
<rollno>3</rollno>
<name>Student Name 3</name>
</student> </students> |
public class StudentModel
{ public List<StudentDetail> StudentDetailList { get; set; }
}
public class StudentDetail
{ public int RollNo
{ get; set; } public string StudentName { get; set; } } |
[HttpGet] public IActionResult Index() { StudentModel studentModel = new StudentModel(); studentModel.StudentDetailList = new List<StudentDetail>(); string xmlfilepath = Path.Combine(Directory.GetCurrentDirectory(), "XMLFiles", "StudentXML.xml"); var xmlString = System.IO.File.ReadAllText(xmlfilepath); var stringReader = new StringReader(xmlString); var dsSet = new
System.Data.DataSet(); dsSet.ReadXml(stringReader); for (int i = 0;
i < dsSet.Tables[0].Rows.Count; i++) {
studentModel.StudentDetailList.Add(new StudentDetail { RollNo = (int)dsSet.Tables[0].Rows[i][0], StudentName = dsSet.Tables[0].Rows[i][1].ToString() }); } return View(studentModel); } |
@model Project.Models.StudentModel @{
ViewData["Title"] = "Home Page"; } @using (Html.BeginForm("Index", "Home", FormMethod.Post,
new { @id = "formxmldata", @enctype = "multipart/form-data" })) {
<table class="table"> <thead> <tr> <th>Roll No</th> <th>Student Name</th> </tr> </thead> <tbody> @foreach (var item in
Model.StudentDetailList) { <tr> <td>@item.RollNo</td> <td>@item.StudentName</td> </tr> } </tbody>
</table> } |
Download
0 comments:
Please let me know your view