Title | Load Structures from an XML file in Visual Basic 2005 |
Description | This example shows how to load Structures from an XML file in Visual Basic 2005. |
Keywords | XML, structure, load, file, Item, initialize, initialization |
Categories | Files 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:
|
|
<Class>
<App1>
<Project1>
<Client>Client A</Client>
<City>City A</City>
<State>AA</State>
</Project1>
<Project2>
<Client>Client B</Client>
<City>City B</City>
<State>BB</State>
</Project2>
</App1>
<App2>
<Project3>
<Client>Client C</Client>
<City>City C</City>
<State>CC</State>
</Project3>
<Project4>
<Client>Client D</Client>
<City>City D</City>
<State>DD</State>
</Project4>
</App2>
</Class>
|
|
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 _
String)
lstUsers.Items.Clear()
Dim xml_doc As New XmlDocument
xml_doc.Load(file_name)
' 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 _
app_node.ChildNodes
' 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.
new_user.ReadFromXml(project_node)
' Add it to the ListBox.
lstUsers.Items.Add(new_user)
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.
|
|
|
|