Writing and reading xml files
- Creating and Writing into XML files
- Reading XML files
in this part 2 of my tutorial we will study on how to read what is inside the xml files, we are still going to use the project that we've created at the part I. In the first part we use the form load event to create a xml file and at the same time write something into it. In this tutorial we will be using the button1 click event.
Double click the button1 in design view. You should see something like this
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click End Sub
Inside that subroutine paste this code
'check if file myxml.xml is existing If (IO.File.Exists("MyXML.xml")) Then 'create a new xmltextreader object 'this is the object that we will loop and will be used to read the xml file Dim document As XmlReader = New XmlTextReader("MyXML.xml") 'loop through the xml file While (document.Read()) Dim type = document.NodeType 'if node type was element If (type = XmlNodeType.Element) Then 'if the loop found a <FirstName> tag If (document.Name = "FirstName") Then TextBox1.Text = document.ReadInnerXml.ToString() End If 'if the loop found a <LastName tag If (document.Name = "LastName") Then TextBox2.Text = document.ReadInnerXml.ToString() End If End If End While Else MessageBox.Show("The filename you selected was not found.") End If
explanations are inside the code above and commented it's easy to follow right?
This kind of technique was useful because you can use it to store your settings, connectionstrings for database connection, save username/password for textbox "Remember me" something like that? you can simply read and write into it if ever you want to change the settings, you can just open the xml file whenever and wherever you want without opening the source code of the program. I will be attaching the complete program below. Feel free to download it and make some discovery and experiments
xmlPractice.zip 73.31KB 1016 downloads