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

Article translations Article translations
Article ID: 301232 - View products that this article applies to.
This article was previously published under Q301232
Expand all | Collapse all

On This Page

Summary

This article demonstrates how to use the XmlTextReader class to read Extensible Markup Language (XML) from a URL. The streamed information can come from a variety of sources, such as a byte stream from a server, a file, or a TextReader class.

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 XML
  • URLs and creating an XML endpoint

How to read XML data from a URL

This example uses a file named Books.xml. You can create your own Books.xml file or use the sample file that is included with the .NET Software Development Kit (SDK) QuickStarts. Books.xml is also available for download; refer to the References section for the download location.
  1. Copy Books.xml to the \Inetpub\Wwwroot folder on your computer.
  2. Open Visual Studio .NET
  3. Create a new Visual Basic .NET Console Application. You can proceed to the complete code listing or continue through these steps to build the application.
  4. Make sure that the project contains a reference to the System.Xml namespace.
  5. 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
    					
  6. Retrieve the XML stream through a URL. Streams are used to provide independence from the device; thus, no program changes are required if the source of a stream changes. Declare a constant for the http://localhost/books.xml URL. You will use this in the next step with the XmlTextReader class. Add the following code sample to the Main procedure of the default module:
    const URLString as String = "http://localhost/books.xml"
    					
  7. Create an instance of the XmlTextReader class, and specify the URL. Typically, XmlTextReader is used if you need to access the XML as raw data without the overhead of a Document Object Model (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 a URL:
    Dim reader As XmlTextReader = New XmlTextReader (URLString)
    					
  8. Read through the XML. (Note that this step shows a basic, 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
    					
  9. 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 example displays the name of the elements and the document type. Note that this example ignores element attributes.
    Do While (reader.Read())
    Select Case reader.NodeType
    Case 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 Select
    Loop
    					
  10. 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.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
    					
  11. Build and run your project.

Complete code listing

Imports System.Xml
Module Module1

    Sub Main()
        Const URLString As String = "http://localhost/books.xml"
        Dim reader As XmlTextReader = New XmlTextReader(URLString)
        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


    End Sub

End Module
				

References

The following file is available for download from the Microsoft Download Center:
Collapse this imageExpand this image
Download
Download Books.xml now
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:
http://msdn.microsoft.com/msdnmag/issues/01/01/xml/default.aspx
For more information about the XmlReader class, see the following Microsoft .NET Framework Class Library documentation:
http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(VS.71).aspx
For more information about how to use XmlReader to read XML data, see the following Microsoft .NET Framework Developer's Guide documentation:
http://msdn2.microsoft.com/en-us/library/aa720470(VS.71).aspx

Properties

Article ID: 301232 - Last Review: October 16, 2012 - Revision: 6.0
Applies to
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft Visual Basic .NET 2003 Standard Edition
Keywords: 
kbdownload kbhowtomaster KB301232

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com