Reading an XML file
Recently, I was working on a Windows service where I had to create a custom XML configuration file and read it. So, I figured I'd share how I did it.
XML configuration file:
<?xml version ="1.0" ?>
<Parent>
<Child>
<Node1>Blah1</Node1>
<Node2>Blah2</Node2>
<Node3>Blah3</Node3>
</Child>
<Child>
<Node1>Blah4</Node1>
<Node2>Blah5</Node2>
<Node3>Blah6</Node3>
</Child>
</Parent>
C# Code:
using System.Xml;
XmlDocument configurationFile = new XmlDocument();
string xmlFilePath = Server.MapPath("~/MyFile.xml");
configurationFile.Load(xmlFilePath);
XmlNodeList parentNodeList = configurationFile.SelectNodes("Parent/Child");
foreach (XmlNode childNode in parentNodeList)
{
string node1, node2, node3;
node1 = childNode.SelectSingleNode("Node1").InnerText;
node2 = childNode.SelectSingleNode("Node2").InnerText;
node3 = childNode.SelectSingleNode("Node3").InnerText;
}
VB.NET Code:
Dim configurationFile As New XmlDocument()
Dim xmlFilePath As String = Server.MapPath("~/MyFile.xml")
configurationFile.Load(xmlFilePath)
Dim parentNodeList As XmlNodeList = configurationFile.SelectNodes("Parent/Child")
For Each childNode As XmlNode In parentNodeList
Dim node1, node2, node3 As String
node1 = childNode.SelectSingleNode("Node1").InnerText
node2 = childNode.SelectSingleNode("Node2").InnerText
node3 = childNode.SelectSingleNode("Node3").InnerText
Next
Similar Posts
- Accessing Config File Mail Settings Programmatically
- Sending an email using System.Net.Mail
- Introducing Lullaby





Comments
FusionGuy on on 5.09.2006 at 8:32 AM
You've got typo in the start of the second child element. Should be <Child> not <Chld>
Ryan Olshan on on 5.09.2006 at 8:40 AM
Woopsie. Thanks for pointing that out. It's fixed pending clearing of CS cache.
Ryan