January 2018 : Instructor-led Online Course in ASP.NET Core 2.0. Conducted by Bipin Joshi. Read more...
Registration for January 2018 batch of ASP.NET Core 2.0 instructor-led online course has already started. Conducted by Bipin Joshi. Register today ! Click here for more details.

Convert XML data to JSON and return it from Web API

Recently I stumbled upon a situation where a large number of XML documents needed to be returned from ASP.NET Web API. This sounds like a straightforward task but there was a small twist to the story. The XML documents existed as physical disk files. The Web API should read these files. process them in some way and then convert the XML data into JSON. This was needed because the client applications were designed to handle only JSON format. Here I discuss a quick way to accomplish this task.

If we want to read physical XML files and return the content as it is then that's quite straightforward. Have a look at the following Get() Web API action :

public HttpResponseMessage Get()
{
    string path = HostingEnvironment
.MapPath("~/Employees.xml");

    XmlDocument doc = new XmlDocument();
    doc.Load(path);

    HttpResponseMessage response = this.Request.
CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent
(doc.OuterXml, Encoding.UTF8, "application/xml");
    return response;
}

The XML data is assumed to be residing in Employees.xml file. In order to send this data to the client we need to load the XML document. This requires physical path of the XML file. Notice the use of HostingEnvironment class from System.Web.Hosting namespace and its MapPath() method.

Once we get the physical path we load it in an XmlDocument object using its Load() method. The Employees.xml contains XML markup as shown below :

<?xml version="1.0" encoding="utf-8" ?>
<employees>
  <employee employeeid="1">
    <firstname>Nancy</firstname>
    <lastname>Davolio</lastname>
    <homephone>(206) 555-9857</homephone>
    <notes>
      <![CDATA[Education includes a BA in psychology 
from Colorado State University in 1970. 
She also completed "The Art of the Cold Call." 
Nancy is a member of Toastmasters International.]]>
    </notes>
  </employee>
  ...
  ...
  </employee>
</employees>

In order to return this XML data we wrap it inside HttpResponseMessage object. Notice that the return type of the Get() is also HttpResponseMessage. The CreateResponse() method creates an HttpResponseMessage object with the status code of OK. Further, we add Content to it using a StringContent object. The StringContent gets the XML data through the OuterXml property of the XmlDocument and we also specify the content type as application/xml.

The HttpResponseMessage object is then returned to the caller.

If you run this Web API action in the browser you will get an XML data like this :

So far so good. But now we want to return the XML documents as JSON. How do we do that? Luckily Json.Net component comes to our rescue. It provides methods to serialize and deserialize data between XML and JSON formats. Here, we need to convert XML to JSON. So, let's see how that can be done.

Make sure to add NuGet package for Json.Net component (if it's not already added to the project).

Then modify the Get() Web API action as shown below :

public HttpResponseMessage Get()
{
    string path = HostingEnvironment.MapPath
("~/Employees.xml");

    XmlDocument doc = new XmlDocument();
    doc.Load(path);

    HttpResponseMessage response = this.Request.
CreateResponse(HttpStatusCode.OK);

    string json = JsonConvert.SerializeXmlNode(doc);

    response.Content = new StringContent(json, 
Encoding.UTF8, "application/json");
    return response;
}

The code looks quite similar to the earlier one. But notice the line marked in bold letters. The SerializeXmlNode() method accepts an XmlNode object and returns its JSON equivalent. While creating the StringContent we add this JSON string and set the content type to application/json.

If you run the Web API, this time you will get JSON as expected :

The counterpart of SerializeXmlNode() is DeserializeXmlNode() and it does exactly opposite - takes JSON data and converts it into XML document.

That's it for now! Keep coding !!


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 13 November 2017


Tags : ASP.NET ASP.NET Core MVC C# Visual Studio