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.
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"?>
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.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/xml";
//Read the XML file contents as String.
string xml = System.IO.File.ReadAllText(Server.MapPath("~/XML/Customers.xml"));
There is no programming required inside the View and hence this section is skipped.
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.