In this article I will explain with an example, how to display Formatted XML in Browser in ASP.Net MVC Razor.
The XML file will be read as string and then its contents will be written to the Response as XML which will ultimately display the Formatted XML in Browser in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
XML File
The following is the XML file consisting of records of Customers. The XML file is saved with the name Customers.xml in a folder named XML inside the project folder.
<?xml version="1.0" standalone="yes"?>
<Customers>
  <Customer>
    <Id>1</Id>
    <Name>John Hammond</Name>
    <Country>United States</Country>
  </Customer>
  <Customer>
    <Id>2</Id>
    <Name>Mudassar Khan</Name>
    <Country>India</Country>
  </Customer>
  <Customer>
    <Id>3</Id>
    <Name>Suzanne Mathews</Name>
    <Country>France</Country>
  </Customer>
  <Customer>
    <Id>4</Id>
    <Name>Robert Schidner</Name>
    <Country>Russia</Country>
  </Customer>
</Customers>
 
 
Controller
The Controller consists of one Action method.
Action method for handling GET operation
Inside the Index Action method, first the Response properties are set in which the most important is the Content Type as it informs the Browser about the content we are sending i.e. XML.
Once the Response properties are set, the XML file contents are read as string and then stored in a variable.
Finally, the variable i.e. XML file contents are sent to the Client Browser as string using the Content function.
Note: The Content function sends the data to the Response similar to Response.Write function.
 
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        //Set the Response properties.
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/xml";
 
        //Read the XML file contents as String.
        string xml = System.IO.File.ReadAllText(Server.MapPath("~/XML/Customers.xml"));
        return Content(xml);
    }
}
 
 
View
There is no programming required inside the View and hence this section is skipped.
 
 
Screenshot
Display Formatted XML in Browser in ASP.Net MVC
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads