Click here to Skip to main content
15,881,413 members
Articles / Web Development / ASP.NET / ASP.NET4.0
Tip/Trick

Generate XML in ASP.NET MVC5 and AngularJs using Database Value

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
16 May 2016CPOL2 min read 23.5K   213   8  
This tip will help you to generate .xml file in AngularJs and ASP.NET MVC5 using XElement of C#.

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.
    C#
    @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:
    C#
    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.
    HTML
    <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()".
    XML
    <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.
    JavaScript
    $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) {
        // Set up the link
        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.
    C#
    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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Bangladesh Bangladesh
Worked on ASP.NET MVC, AngularJS, jQuery, T-SQL, LINQ, Kendo UI, SQL Server, Bootstrap. Working on web based application development and fully concentrated on both client side and server side programming.

Comments and Discussions

 
-- There are no messages in this forum --