You are currently offline, waiting for your internet to reconnect

How to read XML from a file by using Visual Basic .NET

This article was previously published under Q301225
For a Microsoft Visual C# .NET version of this article, see 307548.

IN THIS TASK

Summary
This article demonstrates how to use the XmlTextReader class to read Extensible Markup Language (XML) from a file. XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 specification as well as the namespaces in XML specification from the World Wide Web Consortium (W3C). This article provides fast, tokenized stream access to XML rather than using an object model such as the XML Document Object Model (DOM).

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
  • XML terminology
  • Creating and reading an XML file
back to the top

How to read XML from a file

This example uses a file named Books.xml. You can create your own Books.xml file. You must copy Books.xml to the \Bin\Debug folder that is located under the folder in which you create this project. Books.xml is also available for download; refer to the References section for the download location.
  1. Open Visual Studio .NET
  2. Create a new Visual Basic .NET Console Application. You can proceed directly to the Complete Code Listing section or continue through these steps to build the application.
  3. Make sure that the project contains a reference to the System.Xml.dll assembly.
  4. Use the Imports statement on the Xml namespace so that you are not required to qualify XmlTextReader declarations later in your code. You must use the Imports statement prior to any other declarations.
    Imports System.Xml					
  5. Construct an XmlTextReader class with the XML file. Typically, XmlTextReader is used if you need to access the XML as raw data without the overhead of a DOM; thus, XmlTextReader provides a faster mechanism for reading XML. XmlTextReader has different constructors to specify the location of the XML data. The following code loads XmlTextReader from the Books.xml file. Add the following code to construct XmlTextReader in the Main procedure of Module1:
    Dim reader As XmlTextReader = New XmlTextReader ("books.xml")					
  6. Read through the XML. Note that this step shows an outer "while" loop, and the next two steps show how to use that loop and read XML. After it is loaded, XmlTextReader performs sequential reads to move across the XML data and uses the Read method to get the next record. The Read method returns false if there are no more records.
    Do While (reader.Read())    ' Do some work here on the data.    Console.WriteLine(reader.Name)Loop' Reading of the XML file has finished.Console.ReadLine() 'Pause					
  7. Inspect the nodes. To process the XML data, each record has a node type, which can be determined from the NodeType property. The Name and Value properties return the node name (the element and attribute names) and the node value (the node text) of the current node (or record). The NodeType enumeration determines the node type. The following sample code displays the name of the elements and the document type. Note that this sample ignores element attributes.
    Do While (reader.Read())Select Case reader.NodeTypeCase XmlNodeType.Element 'Display beginning of element.Console.Write("<" + reader.Name)Console.WriteLine(">")Case XmlNodeType.Text 'Display the text in each element.Console.WriteLine(reader.Value)Case XmlNodeType.EndElement 'Display end of element.Console.Write("</" + reader.Name)Console.WriteLine(">")End SelectLoop					
  8. Inspect the attributes. Element node types can include a list of attribute nodes that are associated with them. The MovetoNextAttribute method moves sequentially through each attribute in the element. Use the HasAttributes property to test whether the node has any attributes. The AttributeCount property returns the number of attributes for the current node.
    Do While (reader.Read())Select Case reader.NodeTypeCase XmlNodeType.Element 'Display beginning of element.Console.Write("<" + reader.Name)         If reader.HasAttributes Then 'If attributes exist         	While reader.MoveToNextAttribute() 					'Display attribute name and value.Console.Write(" {0}='{1}'", reader.Name, reader.Value)End WhileEnd IfConsole.WriteLine(">")Case XmlNodeType.Text 'Display the text in each element.Console.WriteLine(reader.Value)Case XmlNodeType.EndElement 'Display end of element.Console.Write("</" + reader.Name)Console.WriteLine(">")End SelectLoop					
  9. Save and close your project.
back to the top

Complete code listing

Imports System.XmlModule Module1    Sub Main()        Dim reader As XmlTextReader = New XmlTextReader("books.xml")        Do While (reader.Read())            Select Case reader.NodeType                Case XmlNodeType.Element 'Display beginning of element.                    Console.Write("<" + reader.Name)                    If reader.HasAttributes Then 'If attributes exist                        While reader.MoveToNextAttribute()                            'Display attribute name and value.                            Console.Write(" {0}='{1}'", reader.Name, reader.Value)                        End While                    End If                    Console.WriteLine(">")                Case XmlNodeType.Text 'Display the text in each element.                    Console.WriteLine(reader.Value)                Case XmlNodeType.EndElement 'Display end of element.                    Console.Write("</" + reader.Name)                    Console.WriteLine(">")            End Select        Loop        Console.ReadLine()    End SubEnd Module				

Output

<bookstore><book><title>The Autobiography of Benjamin Franklin</title><author><first-name>Benjamin</first-name><last-name>Franklin</last-name></author><price>8.99</price></book><book><title>The Confidence Man</title><author><first-name>Herman</first-name><last-name>Melville</last-name></author><price>11.99</price></book><book><title>The Gorgias</title><author><name>Plato</name></author><price>9.99</price></book></bookstore>				
back to the top
References
The following file is available for download from the Microsoft Download Center:
For more information, see the "XML in .NET: .NET Framework XML Classes and C# Offer Simple, Scalable Data Manipulation" article from MSDN Magazine at the following Microsoft Web site: For more information about the XmlReader class, see the following Microsoft .NET Framework Class Library Web site: For more information about how to use XmlReader to read XML data, see the following Microsoft .NET Framework Developer's Guide documentation:  back to the top
dotnet xml
Properties

Article ID: 301225 - Last Review: 10/15/2012 07:24:00 - Revision: 5.0

  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • kbdownload kbhowtomaster KB301225
Feedback