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