Reader Level:
Articles

Reading XML Files using XmlDocument in VB.NET

By Bulent Ozkir on November 10, 2012
In this article, I will show you how to read XML files in VB.NET using XmlDocument class and its members.
  • 0
  • 0
  • 41658

Suppose I have following XML fragment:

<Authors> 
<Author>
<
FirstName>John</FirstName>
<
LastName>Doe</LastName>
</
Author>
<
Author>
<
FirstName>Jane</FirstName>
<
LastName>Eod</LastName>
</
Author>
</
Authors>

Now, how can I loop through my collection of authors and for each author  retrieve its first and last name and put them in a variable strFirst and  strLast?

Imports System
Imports System.Xml
Public Class XMLApp
Public Sub YourMethod(ByVal strFirst As [String], ByVal strLast As [String])
' Do something with strFirst and strLast.
Console.WriteLine("{0}, {1}", strLast, strFirst)
End Sub 'YourMethod
Public Sub ProcessXML(ByVal xmlText As [String])
Dim _doc As New XmlDocument
_doc.LoadXml(xmlText)
' alternately, _doc.Load( _strFilename); to read from a file.
Dim _fnames As XmlNodeList = _doc.GetElementsByTagName("FirstName")
Dim _lnames As XmlNodeList = _doc.GetElementsByTagName("LastName")
' I'm assuming every FirstName has a LastName in this example, your requirements may vary. // for ( int _i = 0; _i < _fnames.Count; ++_i )
If (True) Then
YourMethod(_fnames(_i).InnerText, _lnames(_i).InnerText)
End If
Dim
 Main As [String]()
If (True) Then
Dim
 _app As New XMLApp
' Passing XML text as a String, you can also use the
' XMLDocument::Load( ) method to read the XML from a file.
_app.ProcessXML(" <Authors> 
<Author> 
<FirstName>John</FirstName>
<LastName>Doe</LastName>
</Author>
<Author>
<FirstName>Jane</FirstName>
<LastName>Eod</LastName>
</Author>
</Authors> ")
End If
End
 Sub 'ProcessXML
End Class 'XMLApp
' end XMLApp

XMLApp.vb

Remember to /reference the System.Xml.dll on the command-line  to build XMLApp.vb: vbc.exe /r:System.Xml.dll XMLApp.vb.

COMMENT USING

Trending up