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
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();
xmlDoc.Load(reader);
reader.Close();
lbNodes.Items.Add("XML Document");
XmlNode xnod = xmlDoc.DocumentElement;
AddWithChildren(xnod,1);
}
private void AddWithChildren(XmlNode xnod, Int32 intLevel)
{
XmlNode xnodWorking;
String strIndent = new string(' ',2 * intLevel);
string strValue = (string) xnod.Value;
if(strValue != null)
{
strValue = " : " + strValue;
}
lbNodes.Items.Add(strIndent + xnod.Name + strValue);
if (xnod.NodeType == XmlNodeType.Element)
{
XmlNamedNodeMap mapAttributes = xnod.Attributes;
foreach(XmlNode xnodAttribute in mapAttributes)
{
lbNodes.Items.Add(strIndent + " " + xnodAttribute.Name +
" : " + xnodAttribute.Value);
}
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.