Saturday, July 13, 2013

HOW TO: Read an XML file in ASP.NET/C#

XML is used almost everywhere these days to facilitate sharing data between applications, between application layers or simply as data storage. This post shows you a basic method of reading an XML file in ASP.NET and display the output on an .aspx page. We will take the following xml as an example that has information about book such as title, ISBN, and author.

<?xml version="1.0" encoding="utf-8" ?>
    <Title>Programming Microsoft ASP.NET 4</Title>
    <Author>Dino Esposito</Author>
    <Title>Microsoft Visual C# 2010 Step by Step</Title>
    <Author>John Sharp</Author>
    <Title>Programming Microsoft ADO.NET Core Reference</Title>
    <Author>David Sceppa</Author>

Here is the C# code to read the above XML file which is stored in the root application folder in the attached example and display the data on the page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Data;
using System.Xml;
using System.Text;
public partial class Default8 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            //Bind Data to Gridview
    // This method is used to get xml node values and bind to gridview
    private void readXML()
        XmlDocument doc = new XmlDocument();
        //Load XML from the file into XmlDocument object
        XmlNode root = doc.DocumentElement;
        StringBuilder sb = new StringBuilder();
	//Select all nodes with the tag Book
        XmlNodeList nodeList = root.SelectNodes("Book");
	//Loop through each node under the node “Book”
        foreach (XmlNode node in nodeList)
            sb.Append("Title: ");
	    //Select the text from a single node, “Title” in this case
            sb.Append("ISBN: ");
            sb.Append("Author: ");


Post a Comment