Articles in this section
Category / Section

How to process xml data from server using DataManager?

1 min read

Problem

How to process the XML response from server and bound the result to Grid?

Solution

Essential Javascript DataManager works well with JSON data, but when comes with xml, we need custom adaptor to achieve this requirement. In the custom adaptor, the processResponse has to be overridden to process the xml response from the server.

In the below code snippet, we have extended processResponse method of the ej.UrlAdaptor and in the extended method, the xml data from the server is converted into JSON array. Now it can bound with grid. In the following code, we have performed simple Xml to Json conversion in the function “ConvertToJSON”, which will parse the simple xml document to json, for complex xml parsing, you can use external libraries.

<script>
    function gridLoad(args) {
        this.model.dataSource.adaptor = new xmlAdaptor();
    }
     //for webforms use ej.WebMethodAdaptor
    var xmlAdaptor = new ej.UrlAdaptor().extend({
        //Overriding default processResponse function
        processResponse: function (data, ds, query, xhr, request, changes) {
            return processXML(data);
        }
    });
 
    function processXML(ele) {
        var json = ConvertToJSON(ele);
        return json.Orders.OrderDetails;
    }
    //Function to convert XML document to JSON object
    function ConvertToJSON(ele) {
        var json = {}, e, ch;
        var addItem = function (parent, name, value) {
            if (!parent[name])
                parent[name] = value;
            else {
                if (parent[name].constructor != Array)
                    parent[name] = [parent[name]];
                parent[name][parent[name].length] = value;
            }
        }
 
        for (e = 0, ch = ele.childNodes; e < ch.length; e++) {
            if (ch[e].nodeType == 1) {
                if (ch[e].childNodes.length == 1 && ch[e].firstChild.nodeType == 3)
                    addItem(json, ch[e].nodeName, ch[e].firstChild.nodeValue);
                else if (ch[e].childNodes.length != 0)
                    addItem(json, ch[e].nodeName, ConvertToJSON(ch[e]));
            }
        }
        return json;
    }
 
</script>

 

 

Now let us see, how to use the above custom adaptor (named xmlAdaptor) in the grid. Render the grid and assign the custom adaptor to the grid datasource in the grid Load event.

Grid Initialization

JS

 
<div id="OrdersGrid"></div>
 
<script>
 
    $(function () {
 
        $("#OrdersGrid").ejGrid({
            ej.DataManager({ url: "Home/GetXMLData", dataType: "xml", adaptor: new ej.UrlAdaptor(), offline: true }),
            allowPaging: true,
            columns: [{ field: "OrderID" },
                { field: "CustomerID" },                
                { field: "EmployeeID" },
                { field: "Freight", format:"{0:C2}" },
                { field: "ShipCity" }
            ],
            load: "gridLoad"
        });
 
 
    });
 
</script>
 

 

Razor:

@using Syncfusion.JavaScript.Models
 
 
@(Html.EJ().Grid<OrdersView>("Grid")
    .AllowPaging()
    .Datasource(ds =>
    {
        ds.URL("/Home/UrlDataSource");
        ds.DataType("xml");
        ds.Offline(true);
        ds.Adaptor(AdaptorType.UrlAdaptor);
    })
    .AllowSorting()
    .Columns(col =>
    {
        col.Field("OrderID").Add();
        col.Field("EmployeeID").Add();
        col.Field("Freight").Format("{0:C}").Add();
        col.Field("CustomerID").Add();
        col.Field("ShipCity").Add();
    })
        .ClientSideEvents(events => events.Load("gridLoad"))
)

 

 

 
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public XDocument UrlDataSource(DataManager dm)
        {
            //mention content type as xml
            Response.ContentType = "text/xml";
            XDocument doc = GetXmlDoc();
            return doc;
        }
    }

 

Webforms:

    <ej:Grid ID="Grid" runat="server" AllowPaging="true" >
        <DataManager URL="Default.aspx/UrlDataSource" Offline="true" DataType="xml" Adaptor="WebMethodAdaptor" />
        <Columns>
            <ej:Column Field="OrderID" />
            <ej:Column Field="EmployeeID" />
            <ej:Column Field="Freight" Format ="{0:C2}"/>
            <ej:Column Field="CustomerID" />
            <ej:Column Field="ShipCity" />
        </Columns>
        <ClientSideEvents Load="gridLoad" />
    </ej:Grid>

 

namespace sqlbinding
{
    public partial class _Default : Page
    { 
        [WebMethod]
        //mention content type as xml
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        public static string UrlDataSource(DataManager value)
        {
            
            XDocument doc = GetXmlDoc();
            return doc.ToString();
        }
    }
 }

 

Angular 2 with MVC backend

Index.cshtml
 
<ej-app>Loading...</ej-app>
 
grid.component.html
 
<ej-grid [allowPaging]="true" [dataSource]="gridData">
    <e-columns>
        <e-column field="OrderID"></e-column>
        <e-column field="EmployeeID" ></e-column>
        <e-column field="CustomerID" ></e-column>
        <e-column field="Freight" format="{0:C}"></e-column>
        <e-column field="ShipCity"></e-column>
    </e-columns>
</ej-grid>

 

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
 
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    public gridData: any;
    public foreigndata: any;
    public xmlAdaptor: any;
    constructor() {
        this.xmlAdaptor = new ej.UrlAdaptor().extend({
            //Overriding default processResponse function
            processResponse: $.proxy(function (data, ds, query, xhr, request, changes)        {
                return this.processXML(data);
            },this)
        });
        debugger;
        this.gridData = new ej.DataManager({
            url: "../Home/UrlDataSource",
            offline: true,
            dataType: "xml",
            adaptor: new this.xmlAdaptor
        })
    }
    processXML(ele): any {
        var json = this.ConvertToJSON(ele);
        return json["Orders"].OrderDetails;
    }
    //Function to convert XML document to JSON object
    ConvertToJSON(ele) {
        var json = {}, e, ch;
        var addItem = function (parent, name, value) {
            if (!parent[name])
                parent[name] = value;
            else {
                if (parent[name].constructor != Array)
                    parent[name] = [parent[name]];
                parent[name][parent[name].length] = value;
            }
        }
 
        for (e = 0, ch = ele.childNodes; e < ch.length; e++) {
            if (ch[e].nodeType == 1) {
                if (ch[e].childNodes.length == 1 && ch[e].firstChild.nodeType == 3)
                    addItem(json, ch[e].nodeName, ch[e].firstChild.nodeValue);
                else if (ch[e].childNodes.length != 0)
                    addItem(json, ch[e].nodeName, this.ConvertToJSON(ch[e]));
            }
        }
        return json;
    }
}
 

 

namespace Angular2WebApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public XDocument UrlDataSource(DataManager dm)
        {
            //mention content type as xml
            Response.ContentType = "text/xml";
            XDocument doc = GetXmlDoc();
            return doc;
        }
    }
}

 

Asp.Net core:

<ej-grid id="Grid" allow-paging="true" allow-sorting="true">
    <e-datamanager url="/Home/DataSource" offline="true" data-type="xml" adaptor="UrlAdaptor"/>
    <e-columns>
        <e-column field="OrderID"></e-column>
        <e-column field="EmployeeID"></e-column>
        <e-column field="CustomerID"></e-column>
        <e-column field="Freight" format="{0:C2}"></e-column>
        <e-column field="ShipCity"></e-column>
    </e-columns>
</ej-grid>

 

 
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public XDocument UrlDataSource(DataManager dm)
        {
            //mention content type as xml
            Response.ContentType = "text/xml";
            XDocument doc = GetXmlDoc();
            return doc;
        }
    }

 

Figure 1. Response from the server as XML

 

Figure 2. Grid with data from XML source


Note

A new version of Essential Studio for ASP.NET is available. Versions prior to the release of Essential Studio 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio for ASP.NET. Although Syncfusion will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below.

You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied