Introduction
This tip will help us to use basic C# and .NET features to generate .XML file in MVC5. It will also help us to generate .XML using AngularJs also. We will use only XElement
of C#.
Code Part
Let's say we have a database table named t_Employee
. Employee
table has 4 properties (Name
, Designation
, Email
, Address
).
Using C# in MVC5
- At first, add a button to generate XML from database.
@Html.ActionLink("Generate XML", "GenerateXml", "Employee", new {@class="btn btn-default"})
- Then, create an action in your controller (in this case,
GenerateXml
action in Employee
controller)
- LINQ is used here to get the employee list from database (you can use your own way of getting data from DB)
- And after that, generate your XML using
XElement
in that action like below:
public void GenerateXml()
{
var infoList = (from item in db.t_Employee
select item).ToList();
var count = 1;
var doc = new XElement("EMPLOYEE");
foreach (var item in infoList)
{
doc.Add(new XElement("EMPLOYEE_INFO",
new XElement("SLNO", count),
new XElement("NAME", item.Employee_Name),
new XElement("DESIGNATION", item.Employee_Designation),
new XElement("EMAIL", item.Employee_Email),
new XElement("ADDRESS", item.Employee_Address)
)
);
count += 1;
}
string fileName = "C#_EmployeeInfo_" +
string.Format("{0:yyyy_MM_dd}", DateTime.Now) + ".xml";
Response.ContentType = "text/xml";
Response.AddHeader("content-disposition", "attachment;
filename=\"" + fileName + "\"");
Response.Write(doc);
Response.End();
}
- Here,
EMPLOYEE
is the base element of the XML. EMPLOYEE_INFO
is the immediate child of EMPLOYEE
. Then, other elements are the children of EMPLOYEE_INFO
. You can organize your XML the way you want. This is just a format.
Using AngularJs
For angularJs, XML document generation procedure will be the same as previous. But there will be some addition and slight change in the code part. The procedures are shown below.
Here, we will show how you can pass a value to server side by which you can filter or narrow down your XML data (let's say you want to generate XML using an email). We will use a textBox
to get the input of that email.
- First, we need to add a text box to our page from which we will get our email input.
<input type="text" class="form-control" ng-model="email"/>
- Then we have to add a button to our angular page and give it an angular directive
ng-click
. In this case, we will use ng-click="GenerateXml()"
.
<button type="button" class="btn btn-success-outline"
ng-click="GenerateXml(email)">Export XML</button>
- Now in your script file, create the following
script
functions inside your angular controller.
$scope.GenerateXml = function (email) {
$http({
traditional: true,
url: "/Employee/GenerateXmlUsingAngular",
method: 'POST',
data: JSON.stringify({ email: email }),
contentType: "application/json",
dataType: "json"
}).success(function (data) {
$scope.DownloadXml(data.fileName, data.xmlData);
}).error(function (data) {
alert("Could not generate XML data!");
});
};
$scope.DownloadXml = function (filename, data) {
var link = document.createElement("a");
link.setAttribute("target", "_blank");
if (Blob !== undefined) {
var blob = new Blob([data], { type: "text/xml" });
link.setAttribute("href", URL.createObjectURL(blob));
} else {
link.setAttribute("href", "data:text/xml," + encodeURIComponent(data));
}
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
- Then, we need to create an action
GenerateXmlUsingAngular
in our Employee
controller in which we will generate our XML and return the desired name of the XML file and the XML data as string
. Remember, angularJs will get those two data in Json format.
public JsonResult GenerateXmlUsingAngular(string email)
{
var infoList = (from item in db.t_Employee
where item.Employee_Email == email
select item).ToList();
var count = 1;
var doc = new XElement("EMPLOYEE");
foreach (var item in infoList)
{
doc.Add(new XElement("EMPLOYEE_INFO",
new XElement("SLNO", count),
new XElement("NAME", item.Employee_Name),
new XElement("DESIGNATION", item.Employee_Designation),
new XElement("EMAIL", item.Employee_Email),
new XElement("ADDRESS", item.Employee_Address)
)
);
count += 1;
}
string fileName = "Angular_EmployeeInfo_" +
string.Format("{0:yyyy_MM_dd}", DateTime.Now);
var xmlData = doc.ToString();
return Json(new { fileName, xmlData }, JsonRequestBehavior.AllowGet);
}
Note: Here, we used JsonResult
as the return type of this action. But we can use ActionResult
as well.
- Now run the project and generate XML using the desired email.
Another Trick: We can also generate XML using AngularJs without any filter. To do that, we just need to remove the email from our button click directive ng-click="GenerateXml(email)"
and then angular function $scope.GenerateXml = function(email){}
and then from our mvc action public JsonResult GenerateXmlUsingAngular(string email){}
and finally from the query of infoList
.
History
- Project file has been uploaded for better understanding