Tuesday, September 10, 2013

Read XML File

Read XML File

Example in visual basic of XML reader

Here is and example of code to read a very basic XML file. It uses XmlTextReader to circle over each XML elements. This code also uses XmlNodeType to differentiate the type of information inside the XML file.

The code is simple and has basic security precaution. It checks if the file exist. I also use Fileinfo to keep the filename instead of a regular string. With the Fileinfo object, I could have the file size and other useful information in case something goes wrong in the reading.


Download the sample project here:  XMLReaderSample.zip


Imports System.Xml

''' <summary>
''' This is a sample, very basic, reads XML file.
'''
''' Author : Check-Kay Wong
'''
''' </summary>
''' <remarks></remarks>
Public Class Form1

    Private Sub OpenToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        OpenXML()
    End Sub

    ''' <summary>
    ''' Simple XML reader
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub OpenXML()

        Dim oXmlTextReader As XmlTextReader 'need to Imports System.Xml
        Dim oFileInfo As IO.FileInfo = Nothing

        Try
            'get a XML file
            Using oOpenFileDialog As New OpenFileDialog
                oOpenFileDialog.Filter = "xml file|*.xml|All files|*.*"
                oOpenFileDialog.Multiselect = False
                If oOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
                    If IO.File.Exists(oOpenFileDialog.FileName) Then
                        oFileInfo = New IO.FileInfo(oOpenFileDialog.FileName)
                        'sPath = oOpenFileDialog.FileName

                    End If
                End If

            End Using


            'read the XML file
            If oFileInfo IsNot Nothing Then
                If IO.File.Exists(oFileInfo.FullName) Then
                    oXmlTextReader = New XmlTextReader(oFileInfo.FullName)
                    While oXmlTextReader.Read
                        Select Case oXmlTextReader.NodeType
                            Case XmlNodeType.Element
                                MsgBox(oXmlTextReader.Name)
                            Case XmlNodeType.Text
                                MsgBox(oXmlTextReader.Value)
                            Case XmlNodeType.EndElement
                                MsgBox(oXmlTextReader.Name)
                        End Select
                    End While
                End If
            End If


        Catch ex As Exception

        End Try
      

    End Sub

End Class



No comments:

Post a Comment