Reading and Writing an Xml File the Simple Way

This FAQ introduces you to the world of XML in DotNet. It demonstrates how to use two built-in classes in the dotnet framework for reading and writing xmls. The classes, XmlTextReader and XmlTextWriter, help you to read and write to xmls in a very simple manner.
Language : Visual Basic.Net
Framework : .Net Framework version 1 or 1.1
Imports :

  1. System.Xml

Xml is a subset of SGML. It allows designers to create their own customized tags, enabling the definition, transmission, validation, and interpretation of data between applications and between organizations. Xml in today’s world has become a common standard to store information, especially settings and login information. Most products use Xml to store information which will be needed to run a setup or a load a program’s previously saved configuration’s. Previously we used the Registry and Ini files to store commonly used settings. Now most the applications on the market use Xml to do this. In this FAQ i will explain how to store informtion into xml and get the information back in an extremely simple method.
In Visual Basic if we need to use XML there are basically three methods

  1. DOM
  2. SAX
  3. File Parsing

I will give a brief look into these methods, as covering the whole thing is beyond the scope of this FAQ.

  • Among this DOM was the preferred method as it had a lot of methods that helped the developer to do the needed. Basically DOM had user friendly method names like “getElementsByTagName” and “SelectSingleNode”.
  • SAX was a bit different when compared to DOM. According to the definition given in their website, SAX is the Simple API for XML, originally a Java-only API. SAX was the first widely adopted API for XML in Java, and is a “de facto” standard. The current version is SAX 2.0.1, and there are versions for several programming language environments other than Java.
  • The Third method is just basic simple file parsing. For instance, extract all the tags and the corresponding information using Instr and Mid. This is a tedious method as we have to write the code for all the checking and validation.
    Now we will get to the important part of the FAQ, the classes.
  • 1. XmlTextWriter

    XmlTextWriter belongs to the System.Xml namespace and as the name says, it is used to write Xml files. You might find this similar to the StreamWriter class. Now, in the XmlTextWriter you have couple of methods and properties which we can use to create a perfectly well formed Xml document.

    Well Formed Document means An XML document that follows all rules of XML, but has not necessarily been validated against a DTD(Document Type Definition).

    I won’t go into much detail on DTD. The biggest advantage here is that it does validation of sorts when you are creating the xml document. If the XmlTextwriter detects that you have not closed an element tag which has been opened, it generates an exception. This will help you in creating well-formed Xml Documents. Now we will go into some examples for this class.
    The structure of my xml is as follows:


    In this example i will create an xml document which has shipping id, company name, and phone number. A project created from this walkthrough is attached for reference. Use Vs.Net to create a New project and import the xml namespace.


    Imports System.Xml

    I’ve declared three array variables public in my form and the code is


    Dim arrShipId(2) As String ‘array to store shipping id
    Dim arrCompName(2) As String ‘array to store company name
    Dim arrPhone(2) As String ‘array to store phone no
    Dim XmlPath As String = Application.StartupPath & “\XmlTest.xml” ‘Xml file to be generated

    Then in the form load even, use the following code:


    ‘Storing the values in an array to write to xml
    arrShipId(0) = 1 : arrShipId(1) = 2 : arrShipId(2) = 3
    arrCompName(0) = “Safe Shipping Air Transport Ltd.” : arrCompName(1) = “Equator Private Ltd” : arrCompName(2) = “GreenPeace Pvt. Ltd.”
    arrPhone(0) = “111-123345″ : arrPhone(1) = “222-543321″ : arrPhone(2) = “333-987654″
    ‘Since i didn’t want to complicate things too much, i have stored some statical values. These can be dynamically generated also

    Then drop two buttons on to the form you have just created and name them btnWriteXml and btnReadXml. In btnWriteXml paste the following code


    Dim xmlWriter As New XmlTextWriter(XmlPath, System.Text.Encoding.UTF8)
    Dim iCnt As Int16 xmlWriter.WriteStartElement(“ShipDetails”) ‘Open the Main Parent Node

    For iCnt = 0 To 2
    xmlWriter.WriteStartElement(“Shippers”) ‘Open the Child Parent Node
    xmlWriter.WriteElementString(“ShipperId”, arrShipId(iCnt)) ‘The Child
    xmlWriter.WriteElementString(“CompanyName”, arrCompName(iCnt)) ‘The Child
    xmlWriter.WriteElementString(“Phone”, arrPhone(iCnt)) ‘The Child
    ‘There is no need to close the child tags because the method does it automatically.
    xmlWriter.WriteEndElement() ‘Close the child Parent Node
    xmlWriter.WriteEndElement() ‘Close Main parent Node
    xmlWriter.Close()’close the file
    MsgBox(“Xml File Generated”)

    In the first line I have instantiated an object(xmlWriter) of XmlTextWriter. The parameters that are passed are the filename and the encoding type. When executed, this line will create the required xml without any content.
    Next in line is:
    xmlWriter.WriteStartElement(“ElementName”). This method will create an element (root node) in the xml name. It accepts a string value. Now we have a parent node and according to the structure we also need multiple child-parent nodes. So inside a for loop I have another value being passed onto the WriteStartElement. This will be our child-parent node. Now that we have parent and child parent setup. We will move onto our children. To create the children we will use the WriteElementString method. It basically accepts two parameters

    1. The Element Name
    2. The Element Value

    So we have



    In this sample i have three children ShipperId,CompanyName,Phone. I have it an array loaded in the form load, that’s why i have a for loop to get the values. Now comes the important part remember we had acutally opened two parent tags (ShipDetails,Shippers). We have to make sure we close the document using the WriteEndElement method of the Class. Here try commenting one of the WriteEndElement tags and run the code. The compiler will generate an error saying you gotta close the opening tag. Of course the error description will be more vivid, clear, and Technical.
    Finally we have the close element, which of course closes the file. Well people, we have just written our first xml document. Try opening it IE and voila, there’s the xml file that you just created. It is like a neatly tuned up BMW or Mercedes or whichever car you like . Now we will look under the hood of the car. Roughly translated it means viewing the source of the xml. What, what is that you are seeing, xml content with no indenting. Now that’s not good is it ??. I mean if we have to get the xml file in a readable format we have to do it right ??!!. Well what do you know, the class has another method for us to do this . And they are indenting methods in the XmlWriterClass. Paste the below code right above where you gonna start the main parent element.


    ‘right above ShipDetails Element.
    xmlWriter.IndentChar = vbTab
    xmlWriter.Indentation = 1
    xmlWriter.Formatting = Formatting.Indented

    The first line tells you what the indenting character should be. The second tells you how many indents to give after a line. The third line tells the class to write it to the file in a formatted manner. Well people, that’s XmlWriterClass for ya. Next we will move on to the XmlTextReader Class.

    2. XmlTextReader
    Well as the name says it can be used to read the xml files. And yes it’s very similar to StreamReader class used to read files. This class contains numerous methods to work with xml but we will concern ourselves with only the reading part. Paste the following code in btnReadXml


    Dim xmlReader As New XmlTextReader(XmlPath)
    While (xmlReader.Read)
    Select Case xmlReader.NodeType
    Case XmlNodeType.Element
    MsgBox(“Element Name: ” & xmlReader.Name)
    Case XmlNodeType.Text
    MsgBox(“Element Value: ” & xmlReader.Value())
    End Select
    End While

    Well i think the code is pretty simple, isn’t it? If it isn’t let me explain the code a bit. Well in the first line i am creating an object of XmlTextReader and passing the xml file as input to the reader. Now the xml document is basically composed of elements and their values. In our case we need to find out the element names and its values. The xmlReader objects has method called “NodeType” which helps to determine that whether the current string is a element or text. In short, it will differentiate between the text inside the tags and outside the text. For Instance.



    In the above xml ShippingId is the Element Name and 1 is its value. I am using the while loop to read all the contents of the xml and determine whether the current string is an element or a value. If there is no value then it returns an empty string. Using this simple method we can easily read xml files.


    1. For simplicity sake i have used an array to load content to the xml. You can use whichever method you want to load to the xml.
    2. Some of the definitions that i have given here about SAX, Well-Formed have been taken from google search.

    The XmlTextReader and XmlTextWriter class’ are some of the simplest methods in .net to read and write Xmls. Try out the attachment in this FAQ. You will certainly know what I mean. Hope you find this FAQ useful, and if you think something is wrong or misplaced, please do comment.

    Sourcecode can be downloaded from here Read & Write XML using VB.Net

    0 Responses to “Reading and Writing an Xml File the Simple Way”

    • No Comments

    Leave a Reply