Microsoft KB Archive/301228

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

Article ID: 301228

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft .NET Framework 1.1
 * Microsoft .NET Framework Class Libraries 1.1

-



This article was previously published under Q301228



This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.Xml
 * System.IO

IN THIS TASK
SUMMARY
 * Requirements
 * How to Read XML Data from a Stream

REFERENCES



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.

back to the top

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
 Open Visual Studio .NET. 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. Make sure that the project contains a reference to the System.Xml and System.IO namespace. 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;

 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(&quot;&quot; & _ &quot;&quot; & _ &quot; &quot; & _ &quot; <book genre=&quot;&quot;autobiography&quot;&quot; ISBN=&quot;&quot;1-861003-11-0&quot;&quot;>&quot; & _ &quot;  The Autobiography of Benjamin Franklin &quot; & _ &quot;   &quot; & _ &quot;       <first-name>Benjamin</first-name>&quot; & _ &quot;       <last-name>Franklin</last-name>&quot; & _ &quot;   &quot; & _ &quot;   8.99 &quot; & _ &quot; &quot; & _ &quot; &quot;) C# Code StringReader stream; stream = new StringReader(&quot;<?xml version='1.0'?>&quot; +   &quot;&quot; +    &quot; &quot; +    &quot; <book genre=\&quot;autobiography\&quot; publicationdate=\&quot;1981\&quot; ISBN=\&quot;1-861003-11-0\&quot;>&quot; +    &quot;   The Autobiography of Benjamin Franklin &quot; +    &quot;   &quot; +    &quot;       <first-name>Benjamin</first-name>&quot; +    &quot;       <last-name>Franklin</last-name>&quot; +    &quot;   &quot; +    &quot;   8.99 &quot; +    &quot; &quot; +    &quot; <book genre=\&quot;novel\&quot; publicationdate=\&quot;1967\&quot; ISBN=\&quot;0-201-63361-2\&quot;>&quot; +    &quot;   The Confidence Man &quot; +    &quot;   &quot; +    &quot;       <first-name>Herman</first-name>&quot; +    &quot;       <last-name>Melville</last-name>&quot; +    &quot;   &quot; +    &quot;   11.99 &quot; +    &quot; &quot; +    &quot;  <book genre=\&quot;philosophy\&quot; publicationdate=\&quot;1991\&quot; ISBN=\&quot;1-861001-57-6\&quot;>&quot; + &quot;  The Gorgias &quot; + &quot;  &quot; + &quot;      Plato &quot; + &quot;  &quot; + &quot;  9.99 &quot; + &quot; &quot; + &quot; &quot;);                       </li>  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 (&quot;books.xml&quot;) C# Code System.IO.StreamReader stream = new System.IO.StreamReader (&quot;books.xml&quot;); 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.

</li></ul> </li> 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);

</li> 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;

</li> 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(&quot;<&quot; + reader.Name) Console.WriteLine(&quot;>&quot;) Case XmlNodeType.Text 'Display the text in each element. Console.WriteLine(reader.Value) Case XmlNodeType.EndElement 'Display end of element. Console.Write(&quot;</&quot; + reader.Name) Console.WriteLine(&quot;>&quot;) End Select Loop C# Code while (reader.Read) {   switch (reader.NodeType) {       case XmlNodeType.Element: // The node is an Element. Console.Write(&quot;<&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine (reader.Value); break; case XmlNodeType. EndElement: //Display end of element. Console.Write(&quot;</&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; } }

</li> 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(&quot;<&quot; + reader.Name) If reader.HasAttributes Then 'If attributes exist While reader.MoveToNextAttribute 'Display attribute name and value. Console.Write(&quot; {0}='{1}'&quot;, reader.Name, reader.Value) End While End If Console.WriteLine(&quot;>&quot;) Case XmlNodeType.Text 'Display the text in each element. Console.WriteLine(reader.Value) Case XmlNodeType.EndElement 'Display end of element. Console.Write(&quot;</&quot; + reader.Name) Console.WriteLine(&quot;>&quot;) End Select Loop C# Code while (reader.Read) {   switch (reader.NodeType) {       case XmlNodeType.Element: // The node is an Element. Console.Write(&quot;<&quot; + reader.Name);

while (reader.MoveToNextAttribute) // Read attributes. Console.Write(&quot; &quot; + reader.Name + &quot;='&quot; + reader.Value + &quot;'&quot;); Console.Write(&quot;>&quot;); Console.WriteLine(&quot;>&quot;); break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine (reader.Value); break; case XmlNodeType. EndElement: //Display end of element. Console.Write(&quot;</&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; } }

</li>  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(&quot;books.xml&quot;) Dim reader As XmlTextReader = New XmlTextReader(stream) Do While (reader.Read) Select Case reader.NodeType Case XmlNodeType.Element 'Display beginning of element. Console.Write(&quot;<&quot; + reader.Name) If reader.HasAttributes Then 'If attributes exist While reader.MoveToNextAttribute 'Display attribute name and value. Console.Write(&quot; {0}='{1}'&quot;, reader.Name, reader.Value) End While End If                   Console.WriteLine(&quot;>&quot;) Case XmlNodeType.Text 'Display the text in each element. Console.WriteLine(reader.Value) Case XmlNodeType.EndElement 'Display end of element. Console.Write(&quot;</&quot; + reader.Name) Console.WriteLine(&quot;>&quot;) End Select Loop End Sub

End Module

C# Code

using System; using System.Xml; using System.IO; namespace ReadXMLFromStream {   ///     /// Summary description for Class1. ///    class Class1 {       static void Main(string[] args) {

System.IO.StreamReader stream = new System.IO.StreamReader (&quot;books.xml&quot;); XmlTextReader reader = null; reader = new XmlTextReader (stream); while (reader.Read) {               switch (reader.NodeType) {                   case XmlNodeType.Element: // The node is an Element. Console.Write(&quot;<&quot; + reader.Name);

while (reader.MoveToNextAttribute) // Read attributes. Console.Write(&quot; &quot; + reader.Name + &quot;='&quot; + reader.Value + &quot;'&quot;); Console.Write(&quot;>&quot;); Console.WriteLine(&quot;>&quot;); break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine (reader.Value); break; case XmlNodeType. EndElement: //Display end of element. Console.Write(&quot;</&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; }           }

}   } }

</li> Build and Run your project.</li></ol>

back to the top

<div class="references_section">