5,550,131 members and growing! (19,035 online)
Email Password   helpLost your password?
Languages » XML » XML/XSLT     Intermediate

Reading an XML file using .NET

By Tahir Nasir

An article on how to read an xml file into an ASP.NET page
C#, Windows, .NET, Visual Studio, Dev

Posted: 31 Aug 2003
Updated: 31 Aug 2003
Views: 120,835
Bookmarked: 47 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
34 votes for this Article.
Popularity: 4.36 Rating: 2.84 out of 5
11 votes, 32.4%
1
5 votes, 14.7%
2
4 votes, 11.8%
3
6 votes, 17.6%
4
8 votes, 23.5%
5

Introduction

In this article one will see how we can read and XML file it our ASP.NET application, this trick is use full for making custom configuration files for your application or just reading data stored in an xml file.

Overview

This code uses the XmlTextReader object to read the disk file into the XmlDocument object. the XmlTextReader object has very similar functionality to the StreamReader and BinaryReader objects, except that it is specifically designed to read XML file. The XmlTextReader object also has other XML-specific features. For example the WhitespaceHandling property setting in the code tells it not to create nodes for extra whitespace in the XML file.

The code uses the DocumentElement property of the XmlDocument object to find the node at the root of the tree representation of the XML document. After that, we just recursively call the procedure that adds information about the node to the ListBox control.

The code also deals with attributes. Attribues nodes are not included in the ChildNodes collection of a node in the XmlDocument object. Instead, you can use the Attributes property of the XmlNode object to get a collection of attribute nodes only. The code uses an XmlNamedNodeMap object to hold this collection; this object can hold an arbitrary collection of XmlNode objects of any type.

Code listing

    private void btnLoad_Click(object sender, System.EventArgs e)
    {
      XmlTextReader reader = new XmlTextReader(
        Server.MapPath("mycompany.xml"));
      
      reader.WhitespaceHandling = WhitespaceHandling.None;
      XmlDocument xmlDoc = new XmlDocument();
      //Load the file into the XmlDocument

      xmlDoc.Load(reader);
      //Close off the connection to the file.

      reader.Close();
      //Add and item representing the document to the listbox

      lbNodes.Items.Add("XML Document");
      //Find the root nede, and add it togather with its childeren

      XmlNode xnod = xmlDoc.DocumentElement;
      AddWithChildren(xnod,1);
    }
    
    private void AddWithChildren(XmlNode xnod, Int32 intLevel)
    {
      //Adds a node to the ListBox, togather with its children.

      //intLevel controls the depth of indenting

      XmlNode xnodWorking;
      String strIndent = new string(' ',2 * intLevel);
      //Get the value of the node (if any)

      string strValue = (string) xnod.Value;
      if(strValue != null)
      {
        strValue = " : " + strValue;
      }
      //Add the node details to the ListBox

      lbNodes.Items.Add(strIndent + xnod.Name + strValue);

      //For an element node, retrive the attributes

      if (xnod.NodeType == XmlNodeType.Element)
      {
        XmlNamedNodeMap mapAttributes = xnod.Attributes;
        //Add the attributes to the ListBox

        foreach(XmlNode xnodAttribute in mapAttributes)
        {
          lbNodes.Items.Add(strIndent + " " + xnodAttribute.Name + 
            " : " + xnodAttribute.Value);
        }
        //If there are any child node, call this procedrue recursively

        if(xnod.HasChildNodes)
        {
          xnodWorking = xnod.FirstChild;
          while (xnodWorking != null)
          {
            AddWithChildren(xnodWorking, intLevel +1);
            xnodWorking = xnodWorking.NextSibling;
          }
        }
      }
    }
  }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Tahir Nasir



Occupation: Web Developer
Location: United States United States

Other popular XML articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralConvert java to c#membermayuri1233:18 17 Jun '08  
GeneralThanks...memberCuneyQ4:58 14 Jun '07  
GeneralGOOD ONEmembertkjbbs22:35 1 Jun '07  
Generalproblem in using x-pathmembersusree3:52 23 Sep '03  
GeneralUse the Read method?memberajoshi1:39 3 Sep '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 31 Aug 2003
Editor: Nishant Sivakumar
Copyright 2003 by Tahir Nasir
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project