Read data from an XML file in VB.Net

June 15, 2011 - 12:20

XML is a very flexable file format used to contain data. I often use XML configuration files for applications now instead of a .ini text file, as this type of file is better suited to complex configuration data for your application.

In this example first create an sample XML file containing the data below and save as "config.xml"

<?xml version="1.0" encoding="UTF-8"?>
<Config>
<UserName>test</UserName>
<Password>password</Password>
</Config>


To read in a XML this is done my using the "System.Xml" Class. First the node is selected which contains the data to be read, in this case the "Config" node. Then these sub-nodes which are contained in a node list are cycled through in the For-Next Loop and the Text Retrieved and assigned to Variables.

Dim UserName as String
Dim Password as String

Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument
m_xmld.Load("config.xml")
m_nodelist = m_xmld.SelectNodes("Config")

For Each m_node In m_nodelist
UserName = m_node.Item("UserName").InnerText
Password = m_node.Item("Password").InnerText
Next



© 2011 simplevb.net