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" ?>
<Books>
  <Book>
    <Title>Programming Microsoft ASP.NET 4</Title>
    <ISBN>9780735643383</ISBN>
    <Author>Dino Esposito</Author>
  </Book>
  <Book>
    <Title>Microsoft Visual C# 2010 Step by Step</Title>
    <ISBN>0735626707</ISBN>
    <Author>John Sharp</Author>
  </Book>
  <Book>
    <Title>Programming Microsoft ADO.NET Core Reference</Title>
    <ISBN>073562206X</ISBN>
    <Author>David Sceppa</Author>
  </Book>
</Books>


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 asp.net 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
            readXML();
        }
    }
    // 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
        doc.Load(Server.MapPath("~/SampleXML.xml"));
        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(node.SelectSingleNode("Title").InnerText);
            sb.Append("ISBN: ");
            sb.Append(node.SelectSingleNode("ISBN").InnerText);
            sb.Append("Author: ");
            sb.Append(node.SelectSingleNode("Author").InnerText);
            sb.Append("");
        }
        Response.Write(sb.ToString());
    }
}

0 comments:

Post a Comment