Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

Reading an XML File using .NET

Rate me:
Please Sign up or sign in to vote.
3.22/5 (46 votes)
31 Aug 20031 min read 416.6K   11.7K   73   18
An article on how to read an XML file into an ASP.NET page.

Image 1

Introduction

In this article, we will see how we can read an XML file in our ASP.NET application. This trick is useful 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. Attributes 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

C#
  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 an item representing the document to the listbox
    lbNodes.Items.Add("XML Document");
    //Find the root node, and add it together with its childeren
    XmlNode xnod = xmlDoc.DocumentElement;
    AddWithChildren(xnod,1);
  }

  private void AddWithChildren(XmlNode xnod, Int32 intLevel)
  {
    //Adds a node to the ListBox, together 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, retrieve 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 procedure 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.


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThanx. Pin
Member 1061637310-Mar-15 5:01
Member 1061637310-Mar-15 5:01 
QuestionNeed the license for this article Pin
Member 1046361712-Dec-13 17:16
Member 1046361712-Dec-13 17:16 
AnswerMessage Closed Pin
23-Dec-14 4:11
ali.adravi23-Dec-14 4:11 
QuestionThanks Pin
the_fourth7-Sep-12 20:44
the_fourth7-Sep-12 20:44 
AnswerMessage Closed Pin
31-Dec-14 7:38
ali.adravi31-Dec-14 7:38 
GeneralMy vote of 5 Pin
Ajit Kumar Nayak30-Aug-12 2:55
professionalAjit Kumar Nayak30-Aug-12 2:55 
Questionread and update xml file using VB.NET in an aspx web page Pin
JamesT9-Aug-12 3:32
JamesT9-Aug-12 3:32 
GeneralGr8! Pin
Hammad Kan25-Jun-12 13:01
Hammad Kan25-Jun-12 13:01 
Questionhow can I read xml and store it in a string Pin
kaushik240211-Sep-11 23:57
kaushik240211-Sep-11 23:57 
SuggestionUse System.Xml.Serialization Pin
jrberger30-Jun-11 10:07
jrberger30-Jun-11 10:07 
GeneralMy vote of 1 Pin
nicachipal10-Jul-10 7:19
nicachipal10-Jul-10 7:19 
GeneralProblem when parsing a remote file Pin
persquarefeet19-Mar-09 0:45
persquarefeet19-Mar-09 0:45 
GeneralGreat Article Pin
guineapig23144-Nov-08 6:34
guineapig23144-Nov-08 6:34 
GeneralConvert java to c# Pin
mayuri12317-Jun-08 2:18
mayuri12317-Jun-08 2:18 
GeneralThanks... Pin
CuneyQ14-Jun-07 3:58
CuneyQ14-Jun-07 3:58 
GeneralGOOD ONE Pin
tkjbbs1-Jun-07 21:35
tkjbbs1-Jun-07 21:35 
Generalproblem in using x-path Pin
susree23-Sep-03 2:52
susree23-Sep-03 2:52 
QuestionUse the Read method? Pin
ajoshi3-Sep-03 0:39
ajoshi3-Sep-03 0:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.