Building the Right Environment to Support AI, Machine Learning and Deep Learning
Welcome to today's article! Today I will demonstrate how to work with XML files with VB.NET. We will create an XML file, add nodes and elements onto it, and then remove the nodes and elements.
Introduction to XML
Here is a very nice and detailed explanation of the term 'XML', just in case you have never heard about it.
Open up Visual Studio 2012 and create a new VB.NET Windows Forms application. You may name it anything you like. Design the form to resemble Figure 1.
Figure 1 - Our design
Please note that, although you may name your controls anything you like, I may have named mine differently.
As always, let me start with the necessary Namespaces that we will need today. Add the following namespaces:
Imports System.Xml 'XML Capabilities Imports System.Xml.Serialization 'XML Serialization Abilities Imports System.Text 'StringBuilder
Now, let's add a modular variable that will represent the XML documents we will create and manipulate:
Private xdDoc As New XmlDocument() 'Create Modular XMLDocument Object
Creating an XML File
Behind the button labelled "Create Document" add the following code:
Private Sub btnCreate_Click( sender As Object, e As EventArgs) Handles btnCreate.Click 'Store Hardcoded XML Values xdDoc.LoadXml("<Student><Name>Hannes</Name></Student>") 'Save Document & Auto-Indent Output Dim xtwWriter As New XmlTextWriter("Example.xml", Nothing) xtwWriter.Formatting = Formatting.Indented xdDoc.Save(xtwWriter) xtwWriter.Close End Sub
This code starts with the LoadXml method of the XML document object. In there, I have created a very small XML structured statement. Ultimately, whatever I have entered in there will be the physical XML document's contents. Obviously, there are far more complicated ways to create bigger XML documents, but seeing the fact that this article only serves as an introduction, I won't get too complicated.
I then created an XMLTextWriter object. This object is responsible for writing the above contents to the given file in the given format. Then, I simply save the XML document and close it. really not too complicated now is it?
Reading XML File Contents
Add the following code behind the button labelled "Read Document":
Private Sub btnRead_Click( sender As Object, e As EventArgs) Handles btnRead.Click 'Read XML File Dim xtrReader As New XmlTextReader("Example.xml") Dim sbReadXML As New StringBuilder 'Create StringBuilder Object To Host Contents While xtrReader.Read() 'While The Reader Is Reading The Data Select Case xtrReader.NodeType 'What Type Of XML Data Are We Working With? Case Xml.XmlNodeType.Element 'Is It An Element? sbReadXML.Append(xtrReader.Name) 'Get Element Name Case Xml.XmlNodeType.Text 'Is It Ordinary Text? Get Values 'Add : And The Value Being Read sbReadXML.Append(": ") sbReadXML.Append(xtrReader.Value) 'Add A New Line sbReadXML.AppendLine() End Select End While txtContent.Text = sbReadXML.ToString 'Show Contents End Sub
Here I created a new XMLTextReader object to read the file named Example.xml. I then created a StringBuilder object to gradually append the file's content into one singular string. Inside the While loop I simply detect what type of XML content the reader is busy reading. If it is currently reading an XML Element object, it must store the current element's name. If it is reading the contents of an XML element, in other words, the text value, it must append a colon and the value. This will produce a string such as:
Name : Hannes
Lastly, it outputs the StringBuilder's content into the textbox named txtContent.
Reading XML Element Content
It may seem strange that I am explaining the same thing over, but there is a slight difference. Reading a singular Element is a tad different. How? Well, add the following code behind the button labelled "Read Element":
Private Sub btnReadElement_Click( sender As Object, e As EventArgs) Handles btnReadElement.Click xdDoc.Load("Example.xml") 'Load File 'Select Singular Node Dim xnNode As XmlNode = xdDoc.SelectSingleNode("/Student/Teacher/Name") 'Display Node Value txtContent.Text = xnNode.InnerText End Sub
Here, I loaded the xml file called Example.xml into memory, created an XML node object, and then used its SelectSingleNode method to read the specified XML path, which is the node to read. Lastly, I display the node's InnerText property inside the Textbox.
Adding XML Elements to an Existing XML File
Add the following code behind the "Append Element" button:
Private Sub btnAppend_Click( sender As Object, e As EventArgs) Handles btnAppend.Click xdDoc.Load("Example.xml") 'Load XML File 'Add Surname Element. Dim xeElement As XmlElement xeElement = xdDoc.CreateElement("Surname") xeElement.InnerText = "du Preez" 'Supply Value xdDoc.DocumentElement.AppendChild(xeElement) 'Save Dim xtwWriter As New XmlTextWriter("Example.xml", Nothing) xtwWriter.Formatting = Formatting.Indented xdDoc.Save(xtwWriter) xtwWriter.Close() End Sub
Here, I load the document into memory; then, I make use of the CreateElement method of the document object to name the new element to be added. I specify its value via the InnerText property and use the AppendChild method of DocumentElement to physically add it onto the file. The saving of the document is the same code I used in the very first exercise we did (creating an XML file).
Add the following code:
Private Sub btnAppendNode_Click( sender As Object, e As EventArgs) Handles btnAppendNode.Click xdDoc.Load("Example.xml") Dim xnRoot As XmlNode = xdDoc.DocumentElement 'Determine Root Of XML Document ( Student ) 'Create Two New Elements Dim xeMainElement As XmlElement = xdDoc.CreateElement("Teacher") Dim xeSubElement As XmlElement = xdDoc.CreateElement("Name") xeSubElement.InnerText = "Elmarie" 'Name Element Value Is "Elmarie" xnRoot.AppendChild(xeMainElement) 'Add Teacher To Root xeMainElement.AppendChild(xeSubElement) 'Add Name To Teacher Element 'Save Dim xtwWriter As New XmlTextWriter("Example.xml", Nothing) xtwWriter.Formatting = Formatting.Indented xdDoc.Save(xtwWriter) xtwWriter.Close() End Sub
This code determines the current root element. I then create two elements under each other and specify each element's values. I append the Main Element onto the root, and then append the sub element onto it. It is actually quite simple - you just need to know your supplied XML document's structure.
As you can see, working with XML and VB is not so scary as many people think. If you have this basic knowledge, you will be able to manipulate any XML file, whether it be with my basic demonstration or with more advanced techniques you acquire eventually.
I hope you have enjoyed this short but powerful demonstration. Until next time, this is me signing off!