How To Read XML Data from a Stream in .NET Framework SDK

Article translations Article translations
Article ID: 301228 - View products that this article applies to.
This article was previously published under Q301228
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 stream. The stream 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 will need:
  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, or Windows NT 4.0 Server
  • Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
  • XML terminology
  • Creating and reading XML

How to Read XML Data from a Stream

  1. Open Visual Studio .NET.
  2. Create a new Microsoft Visual Basic (VB) or Microsoft Visual C# Console Application.

    NOTE: The following steps provide a detailed description of how to build the application. You can also go directly to step 10, where completed code is provided.
  3. Make sure that the project contains a reference to the System.Xml and System.IO namespace.
  4. Use the IMPORTS statement on the Xml namespace so that you are not required to qualify XmlTextReader declarations in that namespace later in your code. You must use the IMPORTS statement prior to any other declarations as follows:
    Visual Basic .NET code
    Imports System.Xml
    Imports System.IO
    						
    Visual C# code
    using System.Xml;
    using System.IO;
    						
  5. Create or retrieve the XML stream. A stream is an abstract representation of an input or output device that is the source of, or destination for, data (in this case, XML data). You can write to and read from a stream, which is best visualized as a flow of bytes.

    Streams are used to provide independence from the device and therefore require no program changes if, for example, the source of a stream changes. There are a few different ways to create a stream for the XmlTextReader class. Select one of the following code samples to add to the Main procedure of the default module:
    • Code sample that uses the StringReader object:

      The StringReader object reads characters from strings and takes in a string value during construction.Visual Basic .NET Code
      Dim stream as System.IO.StringReader
      stream = new StringReader("<?xml version='1.0'?>" & _
      "<!-- This file is a book store inventory. -->" & _
      "<bookstore>" & _
      " <book genre=""autobiography"" ISBN=""1-861003-11-0"">" & _
      "   <title>The Autobiography of Benjamin Franklin</title>" & _
      "   <author>" & _
      "       <first-name>Benjamin</first-name>" & _
      "       <last-name>Franklin</last-name>" & _
      "   </author>" & _
      "   <price>8.99</price>" & _
      " </book>" & _
      "</bookstore>")
      						
      C# Code
      StringReader stream;
      stream = new StringReader("<?xml version='1.0'?>" +
      	"<!-- This file represents a fragment of a book store inventory database. -->" +
      	"<bookstore>" +
      	" <book genre=\"autobiography\" publicationdate=\"1981\" ISBN=\"1-861003-11-0\">" +
      	"   <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 genre=\"novel\" publicationdate=\"1967\" ISBN=\"0-201-63361-2\">" +
      	"   <title>The Confidence Man</title>" +
      	"   <author>" +
      	"       <first-name>Herman</first-name>" +
      	"       <last-name>Melville</last-name>" +
      	"   </author>" +
      	"   <price>11.99</price>" +
      	" </book>" +
      	"  <book genre=\"philosophy\" publicationdate=\"1991\" ISBN=\"1-861001-57-6\">" +
      	"   <title>The Gorgias</title>" +
      	"   <author>" +
      	"       <name>Plato</name>" +
      	"   </author>" +
      	"   <price>9.99</price>" +
      	" </book>" +
      	"</bookstore>");
      						
    • Code sample that uses the StreamReader object:

      The StreamReader object is used to read characters from files. It reads in the file name to be read during construction:Visual Basic .NET Code
      Dim stream as System.IO.StreamReader
      ' Loads the XML data in the file books.xml in a new stream.
      stream = New StreamReader ("books.xml")
      						
      C# Code
      System.IO.StreamReader stream = new System.IO.StreamReader ("books.xml");
      						
      Note that the Books.xml file is used here. You can create your own Books.xml file. A sample Books.xml file is also shipped with Visual Studio .Net and the .Net Framework SDK.

  6. Construct an XmlTextReader class with the stream. Typically, XmlTextReader is used if you need to access the XML as raw data without the overhead of a Document Object Model (DOM); therefore, 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 stream:
    Visual Basic .NET Code
    Dim reader As XmlTextReader = New XmlTextReader (stream)
    						
    C# Code
    XmlTextReader reader = null;	
    reader = new XmlTextReader (stream);
    						
  7. Read through the XML. Once loaded, XmlTextReader performs sequential reads to move across the XML data and uses the Read method to get the next record. It returns False if there are no more records.
    Visual Basic .NET Code
    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
    						
    C# Code
    while (reader.Read()) 
    {
        // Do some work here on the data.
        ...
    }
    
    while (reader.Read()) 
    {
        // Do some work here on the data.
    	Console.WriteLine(reader.Name);
    }
    Console.ReadLine();
    						
  8. 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.
    Visual Basic .NET Code
    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
    						
    C# Code
    while (reader.Read()) 
    {
        switch (reader.NodeType) 
        {
            case XmlNodeType.Element: // The node is an Element.
                Console.Write("<" + reader.Name);
       Console.WriteLine(">");
                break;
      case XmlNodeType.Text: //Display the text in each element.
                Console.WriteLine (reader.Value);
                break;
      case XmlNodeType. EndElement: //Display end of element.
                Console.Write("</" + reader.Name);
       Console.WriteLine(">");
                break;
        }
    }
    						
  9. 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.
    Visual Basic .NET Code
    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
    						
    C# Code
    while (reader.Read()) 
    {
        switch (reader.NodeType) 
        {
            case XmlNodeType.Element: // The node is an Element.
                Console.Write("<" + reader.Name);
    
                while (reader.MoveToNextAttribute()) // Read attributes.
                    Console.Write(" " + reader.Name + "='" + reader.Value + "'");
                Console.Write(">");
       Console.WriteLine(">");
                break;
      case XmlNodeType.Text: //Display the text in each element.
                Console.WriteLine (reader.Value);
                break;
      case XmlNodeType. EndElement: //Display end of element.
                Console.Write("</" + reader.Name);
       Console.WriteLine(">");
                break;
        }
    }
    						

  10. Completed code is provided here for your convenience.
    Visual Basic.Net code
    Imports System.Xml
    Imports System.IO
    Module Module1
    
        Sub Main()
            Dim stream As System.IO.StreamReader
            ' Loads the XML data in the file books.xml in a new stream.
            stream = New StreamReader("books.xml")
            Dim reader As XmlTextReader = New XmlTextReader(stream)
            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
    						

    C# Code
    using System;
    using System.Xml;
    using System.IO;
    namespace ReadXMLFromStream
    {
    	/// <summary>
    	/// Summary description for Class1.
    	/// </summary>
    	class Class1
    	{
    		static void Main(string[] args)
    		{
    
    			System.IO.StreamReader stream = new System.IO.StreamReader ("books.xml");
    			XmlTextReader reader = null;	
    			reader = new XmlTextReader (stream);
    			while (reader.Read()) 
    			{
    				switch (reader.NodeType) 
    				{
    					case XmlNodeType.Element: // The node is an Element.
    						Console.Write("<" + reader.Name);
    
    						while (reader.MoveToNextAttribute()) // Read attributes.
    							Console.Write(" " + reader.Name + "='" + reader.Value + "'");
    						Console.Write(">");
    						Console.WriteLine(">");
    						break;
    					case XmlNodeType.Text: //Display the text in each element.
    						Console.WriteLine (reader.Value);
    						break;
    					case XmlNodeType. EndElement: //Display end of element.
    						Console.Write("</" + reader.Name);
    						Console.WriteLine(">");
    						break;
    				}
    			}
    
    		}
    	}
    }
    
    						
  11. Build and Run your project.

REFERENCES

For more information, see the "XML in Microsoft .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, StreamReader, and StringReader classes, see the Microsoft .NET Framework Class Library documentation.

For more information about using XmlReader to read XML data, see the Microsoft .NET Framework Developer's Guide documentation.

Properties

Article ID: 301228 - Last Review: July 15, 2004 - Revision: 3.4
APPLIES TO
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework Class Libraries 1.1
Keywords: 
kbhowtomaster KB301228

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