|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionIn 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. OverviewThis code uses the The code uses the The code also deals with attributes. 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;
}
}
}
}
}
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||