Click here to Skip to main content
11,640,626 members (60,959 online)
Click here to Skip to main content

XML File Parsing in VB.NET

, 21 Aug 2003 804.9K 136
Rate this:
Please Sign up or sign in to vote.
Exploring various methods to parse an XML file in a .NET environment

Introduction

Parsing XML files has always been time consuming and sometimes tricky. .NET framework provides powerful new ways of parsing XML. The various techniques know to parse xml files with .NET framework are using XmlTextReader, XmlDocument, XmlSerializer, DataSet and XpathDocument. I will explore the XmlTextReader and XmlDocument approach here.

The Xml File

Figure 1 outlines the xml file that will be parsed.

<?xml version="1.0" encoding="UTF-8"?>
<family>
  <name gender="Male">
    <firstname>Tom</firstname>
    <lastname>Smith</lastname>
  </name>
  <name gender="Female">
    <firstname>Dale</firstname>
    <lastname>Smith</lastname>
  </name>
</family>
Figure1: Xml file

Parsing XML with XMLTextReader

Using XmlTextReader is appropriate when the structure of the XML file is relatively simple. Parsing with XmlTextReader gives you a pre .net feel as you sequentially walk through the file using Read() and get data using GetAttribute() andReadElementString() methods. Thus while using XmlTextReader it is up to the developer to keep track where he is in the Xml file and Read() correctly. Figure 2 below outlines parsing of xml file with XmlTextReader

Imports System.IO
Imports System.Xml
Module ParsingUsingXmlTextReader
Sub Main()
  Dim m_xmlr As XmlTextReader
  'Create the XML Reader
  m_xmlr = New XmlTextReader("C:\Personal\family.xml")
  'Disable whitespace so that you don't have to read over whitespaces
  m_xmlr.WhiteSpaceHandling = WhiteSpaceHandling.NONE
  'read the xml declaration and advance to family tag
  m_xmlr.Read()
  'read the family tag
  m_xmlr.Read()
  'Load the Loop
  While Not m_xmlr.EOF
    'Go to the name tag
    m_xmlr.Read()
    'if not start element exit while loop
    If Not m_xmlr.IsStartElement() Then
      Exit While
    End If
    'Get the Gender Attribute Value
    Dim genderAttribute = m_xmlr.GetAttribute("gender")
    'Read elements firstname and lastname
    m_xmlr.Read()
    'Get the firstName Element Value
    Dim firstNameValue = m_xmlr.ReadElementString("firstname")
    'Get the lastName Element Value
    Dim lastNameValue = m_xmlr.ReadElementString("lastname")
    'Write Result to the Console
    Console.WriteLine("Gender: " & genderAttribute _
      & " FirstName: " & firstNameValue & " LastName: " _
      & lastNameValue)
    Console.Write(vbCrLf)
  End While
  'close the reader
  m_xmlr.Close()
End Sub
End Module
Figure 2: Xml Parsing with XmlTextReader

Parsing XML with XmlDocument

The XmlDocument class is modeled based on Document Object Model. XmlDocument class is appropriate if you need to extract data in a non-sequential manner. Figure 3 below outlines parsing of xml file with XmlDocument

Imports System.IO
Imports System.Xml
Module ParsingUsingXmlDocument
Sub Main()
  Try
    Dim m_xmld As XmlDocument
    Dim m_nodelist As XmlNodeList
    Dim m_node As XmlNode
    'Create the XML Document
    m_xmld = New XmlDocument()
    'Load the Xml file
    m_xmld.Load("C:\CMS\Personal\family.xml")
    'Get the list of name nodes 
    m_nodelist = m_xmld.SelectNodes("/family/name")
    'Loop through the nodes
    For Each m_node In m_nodelist
      'Get the Gender Attribute Value
      Dim genderAttribute = m_node.Attributes.GetNamedItem("gender").Value
      'Get the firstName Element Value
      Dim firstNameValue = m_node.ChildNodes.Item(0).InnerText
      'Get the lastName Element Value
      Dim lastNameValue = m_node.ChildNodes.Item(1).InnerText
      'Write Result to the Console
      Console.Write("Gender: " & genderAttribute _
        & " FirstName: " & firstNameValue & " LastName: " _
        & lastNameValue)
      Console.Write(vbCrLf)
    Next
  Catch errorVariable As Exception
    'Error trapping
    Console.Write(errorVariable.ToString())
  End Try
End Sub
End Module
Figure 3: Xml Parsing with XmlDocument

Compilation and Result

Make sure you have vbc.exe in your path. From the command prompt go to C:\Personal>. Compile ParsingUsingXmlTextReader.vb and ParsingUsingXmlDocument.vb.

C:\Personal>vbc /out:ParsingUsingXmlTextReadervb.exe ParsingUsingXmlTextReader.vb
C:\Personal>vbc /out:ParsingUsingXmlDocumentvb.exe ParsingUsingXmlDocument.vb

When you run the individual program

C:\Personal>ParsingUsingXmlTextReadervb.exe 

OR

C:\Personal>ParsingUsingXmlDocumentvb.exe

You will see the following result for both

Gender: Male FirstName: Tom LastName: Smith

Gender: Female FirstName: Dale LastName: Smith

Conclusion

There are different ways to parse XML files and the best method depends on your situation and the programming style preferred.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Pratik Desai
Web Developer
United States United States
Architects softwares with emerging technologies that will save time and increase productivity.

You may also be interested in...

Comments and Discussions

 
QuestionVery good for READ, what about WRITE or Update Pin
juno10129-Nov-12 18:58
memberjuno10129-Nov-12 18:58 
AnswerRe: Very good for READ, what about WRITE or Update Pin
Gordan Fitz16-Apr-13 11:41
memberGordan Fitz16-Apr-13 11:41 
GeneralMy vote of 5 Pin
juno10129-Nov-12 18:54
memberjuno10129-Nov-12 18:54 
GeneralMy vote of 1 Pin
vijayKallos21-Aug-11 20:57
membervijayKallos21-Aug-11 20:57 
GeneralRe: My vote of 1 Pin
chiku pandviya21-Aug-12 20:46
memberchiku pandviya21-Aug-12 20:46 
GeneralMy vote of 5 Pin
JasonSelf25-May-11 8:23
memberJasonSelf25-May-11 8:23 
GeneralNeed some help with an XML file that doesn't fit this profile Pin
jonathan glass21-Apr-11 11:00
memberjonathan glass21-Apr-11 11:00 
GeneralMy vote of 5 Pin
veereshp22-Mar-11 22:43
memberveereshp22-Mar-11 22:43 
GeneralThank you! Pin
Ron Donovan27-Oct-09 7:04
memberRon Donovan27-Oct-09 7:04 
GeneralThx for quick tutorial Pin
Jay Thakar19-Oct-09 6:10
memberJay Thakar19-Oct-09 6:10 
This helped me to do some quick XML writing.

Thank you very much.



Visit my blog 'Day as Developer'
Visit my website Jay Thakar
GeneralThanks! Pin
BruceL12-Nov-08 3:05
memberBruceL12-Nov-08 3:05 
QuestionHow To Store Multi-Level XML Docs in Hashtable or Dataset? [modified] Pin
ChrisOTF5-Nov-08 4:36
memberChrisOTF5-Nov-08 4:36 
QuestionXML Sheet with different fields? Pin
j_felder2-Jul-08 9:49
memberj_felder2-Jul-08 9:49 
QuestionStart xmltextreader as certain linenumber? [modified] Pin
magiel_van_gaalen13-Dec-07 14:55
membermagiel_van_gaalen13-Dec-07 14:55 
QuestionHow do I take this deeper? Pin
andyd27312-Nov-07 10:55
memberandyd27312-Nov-07 10:55 
AnswerRe: How do I take this deeper? Pin
andyd27314-Nov-07 7:59
memberandyd27314-Nov-07 7:59 
GeneralNice Pin
keniaa6-Nov-07 4:49
memberkeniaa6-Nov-07 4:49 
Generalproblems including xml content Pin
Big Argus18-Apr-07 13:40
memberBig Argus18-Apr-07 13:40 
GeneralRe: problems including xml content Pin
Vladimir_Davidov19-May-07 23:05
memberVladimir_Davidov19-May-07 23:05 
GeneralWorks fine Pin
rlizarraga12314-Nov-06 6:36
memberrlizarraga12314-Nov-06 6:36 
GeneralGood job Pin
spabhat28-Sep-06 22:58
memberspabhat28-Sep-06 22:58 
QuestionCode does not work Pin
DRSlack3-Sep-06 10:02
memberDRSlack3-Sep-06 10:02 
GeneralHi Pls Help Me Pin
Vibhore198017-Aug-06 10:00
memberVibhore198017-Aug-06 10:00 
QuestionHelp2!!! Problem on reading.. Pin
sprlengchai15-Aug-06 22:13
membersprlengchai15-Aug-06 22:13 
GeneralHelp!!! Problem on reading.. Pin
sprlengchai15-Aug-06 22:11
membersprlengchai15-Aug-06 22:11 
QuestionPerformance? Pin
Niteman8-Dec-05 5:24
memberNiteman8-Dec-05 5:24 
GeneralEver heard of option strict ^^ Pin
softa_jonas12-Nov-05 8:58
membersofta_jonas12-Nov-05 8:58 
GeneralThank You Pin
Mrigesh Rajbhandari2-Jun-05 11:20
sussMrigesh Rajbhandari2-Jun-05 11:20 
Generalnot bad Pin
Anonymous16-May-05 19:01
sussAnonymous16-May-05 19:01 
GeneralSmartdevice application Pin
bo4bo4@hotmail.com7-Oct-04 22:27
sussbo4bo4@hotmail.com7-Oct-04 22:27 
GeneralRe: Smartdevice application Pin
Anonymous31-Jan-05 22:31
sussAnonymous31-Jan-05 22:31 
GeneralRe: Smartdevice application Pin
laithz13-Jun-05 1:21
memberlaithz13-Jun-05 1:21 
GeneralXML Doc Pin
dcostelloe18-Jan-04 10:52
memberdcostelloe18-Jan-04 10:52 
GeneralRe: XML Doc Pin
dcostelloe18-Jan-04 10:54
memberdcostelloe18-Jan-04 10:54 
GeneralGood, but... Pin
Anonymous27-Nov-03 0:58
sussAnonymous27-Nov-03 0:58 
GeneralRe: Good, but... Pin
Pratik Desai1-Dec-03 5:23
memberPratik Desai1-Dec-03 5:23 
GeneralRe: Good, but... Pin
shcheah1-Jan-04 21:15
membershcheah1-Jan-04 21:15 
GeneralGood Start Pin
Anonymous24-Oct-03 13:01
sussAnonymous24-Oct-03 13:01 
GeneralRe: Good Start Pin
shcheah1-Jan-04 21:16
membershcheah1-Jan-04 21:16 
Generaldfsaf Pin
Anonymous19-Sep-03 13:09
sussAnonymous19-Sep-03 13:09 
GeneralRe: dfsaf Pin
shcheah1-Jan-04 21:22
membershcheah1-Jan-04 21:22 
GeneralRe: dfsaf Pin
Anonymous1-Jun-04 10:11
sussAnonymous1-Jun-04 10:11 
GeneralRe: dfsaf Pin
v1227-Aug-04 8:29
memberv1227-Aug-04 8:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150731.1 | Last Updated 22 Aug 2003
Article Copyright 2003 by Pratik Desai
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid