What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleLoad Structures from an XML file in Visual Basic 2005
DescriptionThis example shows how to load Structures from an XML file in Visual Basic 2005.
KeywordsXML, structure, load, file, Item, initialize, initialization
CategoriesFiles and Directories, VB.NET, Internet
This program reads data from an XML file into a series of Structures. This shows the structure's fields:
Public Structure User
    Dim AppClass As String
    Dim Proj As String
    Dim Client As String
    Dim City As String
    Dim State As String

End Structure
This shows a sample of the XML file:
      <Client>Client A</Client>
      <City>City A</City>
      <Client>Client B</Client>
      <City>City B</City>
      <Client>Client C</Client>
      <City>City C</City>
      <Client>Client D</Client>
      <City>City D</City>
Subroutine LoadXmlFileIntoStructures controls the process. It loads the XML file into an XmlDocument. It then finds the Class node root element.

The program then loops through the Class node's children, which are App nodes. It saves each App node's name and then loops through its children, which are Project nodes.

For each Project node, the program creates a new User structure and sets its AppClass and Proj fields. It then calls the structure's ReadFromXml method to make the structure initialize its other fields.

Private Sub LoadXmlFileIntoStructures(ByVal file_name As _

    Dim xml_doc As New XmlDocument

    ' Find the Class node.
    Dim class_node As XmlNode = xml_doc.DocumentElement

    ' Loop through the App nodes.
    For Each app_node As XmlNode In class_node.ChildNodes
        Dim app_name As String = app_node.Name

        ' Loop through the app's Project nodes.
        For Each project_node As XmlNode In _
            ' Create a User structure.
            Dim new_user As New User()

            ' Set the app and project name.
            new_user.AppClass = app_name
            new_user.Proj = project_node.Name

            ' Make it read the rest of its properties.

            ' Add it to the ListBox.
        Next project_node
    Next app_node
End Sub
The User structure's ReadFromXml method simply uses the Project node's Item method to find its field values.
' Read the user's values from the Project node.
Public Sub ReadFromXml(ByVal project_node As XmlNode)
    Me.Client = project_node.Item("Client").InnerText
    Me.City = project_node.Item("City").InnerText
    Me.State = project_node.Item("State").InnerText
End Sub
Note that you may be able to simplify this process by using serialization to load the XML data directly into an object hierarchy. For more information, look into XML serialization and deserialization.
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.