Archive for March, 2010

Retrieving XML value pairs into a collection

Thursday, March 25th, 2010

Retrieving value pairs from an XML file based on an XML defined property (in this case production/test) is shown below:

Example XML file:

<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
<appSettings>
<add key=”env” value=”test” />
</appSettings>
<production>
<add key=”abc_Server” value=”produvtion” />
<add key=”abc_Port” value=”5560″ />
<add key=”abc_User” value=”abcdba” />
<add key=”abc_Password” value=”xxx” />
<add key=”abc_Version” value=”DEFAULT” />
<add key=”DBName” value=”prod” />
<add key=”DBUserName” value=”abcdba” />
<add key=”DBPassword” value=”xxx” />
</production>
<test>
<add key=”abc_Server” value=”dev_env” />
<add key=”abc_Port” value=”6169″ />
<add key=”abc_User” value=”abcdba” />
<add key=”abc_Password” value=”xxx” />
<add key=”abc_Version” value=”DEFAULT” />
<add key=”DBName” value=”dev” />
<add key=”DBUserName” value=”abcdba” />
<add key=”DBPassword” value=”xxx” />
</test>
</configuration>

Retrieve value pairs into a NameValueCollection (remember to reference System.Collections.Specialized) and reference an item:

Dim elem As XmlElement = CType(XmlDoc.SelectSingleNode(“//appSettings/add[@key='env']“), XmlElement)
Dim currentEnv As String = elem.GetAttribute(“value”)
Dim nodeList As XmlNodeList = XmlDoc.GetElementsByTagName(currentEnv)

Settings = New NameValueCollection

Dim oNode As XmlNode
Dim oKey As XmlNode
For Each oNode In nodeList
For Each oKey In oNode.ChildNodes
Settings.Add(oKey.Attributes(“key”).Value, oKey.Attributes(“value”).Value)
Next
Next

ConnectionString = “Data Source=” & appSettings(“DBName”) & “;”