Friday, January 2, 2009

How to read Xml file .NET?

.NET frame work has provided library files which load and read xml file.
System.Xml includes few classes which help to do so.

Before reading an xml file we should load the xml file into memory.
So when we ask to load a xml file we should also provide the path of xml file.
Since xml holds data or information in an organised manner like tags and attributes, so we can read information based on tag name, attribute name etc…
This example is to read and display data from xml file
Xml file :-

<?xml version="1.0" encoding="utf-8" ?>
<Tag ID="1">Tag 1</Tag>
<Tag ID="2">Tag 2</Tag>

The above xml file is saved as “XMLFile.xml”.

Below code is to read the xml file and display the contents onto a label.

Aspx page :-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
<title>Xml File</title>
<form id="form1" runat="server">
<label id="lblTag" runat="server"></label>

Code behind page :-

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text;
public partial class Default3 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
private void ReadXml()
XmlDocument doc = new XmlDocument();
//To load xml file into memory
//Reads all tags from xml file whose tage name is tag
XmlNodeList pList = doc.GetElementsByTagName("Tag");
StringBuilder objStringBuilder = new StringBuilder();
if (pList != null && pList.Count > 0)
XmlNode pNode=null;
objStringBuilder.Append("Tags Inner Text : <br/>");
//Iterating to each node from the node list and reading the
//innert text
for(int i=0;i<pList.Count;i++)
pNode = pList[i];
//Appending inner text from each node
objStringBuilder.Append("Tags Attributes : <br/>");
//Iterating to each node from the node list and reading the
//attributes and there values
for (int i = 0; i < pList.Count; i++)
pNode = pList[i];
//Appending attribute names and values
objStringBuilder.Append(pNode.Attributes[0].Name.ToString()+" : ");
objStringBuilder.Append(pNode.Attributes[0].Value.ToString() + "<br/>");
//Displaying the prepared content onto a html label
lblTag.InnerHtml = objStringBuilder.ToString();

Output :-

No comments:

Post a Comment