This sample illustrates how to read XML from a stream using the XmlTextReader class. The stream could have come from a variety of sources such as a byte stream
from a server, a file or from a TextReader. <br clear="left"><br>
This sample follows on from the <a href="/quickstart/howto/doc/Xml/ReadXmlFile.aspx">How do I...Read XML from a file?</a> topic.
The XmlTextReader has different constructors to specify the location of the XML data. Here we are going to load the XmlTextReader from a 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
a stream and read from a stream, which is best visualised as a flow of bytes. Streams are used to provide independence from the device and hence require
no program changes if, for instance, the source of a stream changes.
<br clear="left"><br>
<div style="width:660">
The sample code shown below creates a StringReader class which is then used to build up an XML string. Since this is purely a byte stream which is held in memory,
we can get the XmlTextReader to parse this stream as XML. This in memory stream has no particular specified encoding. An XmlTextReader is then created which parses
the stream and displays the resultant XML.
<div class="code"><xmp>
StringReader stream;
XmlTextReader reader = null;
stream = new StringReader("<?xml version='1.0'?>" +
"<!-- This file represents a fragment of a book store inventory database -->" +
If a Stream is supplied as input, the XmlTextReader properly decodes this by wrapping the stream in a StreamReader and calling the SwitchEncoding property according
to the XML encoding specified. Also the XmlResolver is used to resolve external resources needed to correctly parse the input - like DTD's, schemas, entities
and <xml:include>s. Another method of representing a stream is by using a StreamReader class that implements a reader which reads from a character stream.
The code sample below illustrates loading a file named books.xml and then using the XmlTextReader to parse the resulting file.</div>
<div class="code"><xmp>
StreamReader streamreader = new StreamReader ("books.xml");
XmlTextReader xmlreader = new XmlTextReader (streamreader);
</xmp></div>
<div style="width:660">
This FormalXml method in this sample shows how to move to the attribute nodes using the <b>MoveToNextAttribute</b> method when the current node is an element
node. This allows you not only to access the node's name and value properties but, because you are at a node context you can also get properties like the current
namespace for the attribute. The code sample below also shows the Format method that this time displays the name and value for the current node.</div>
<div class="code"><xmp>
private static void FormatXml (XmlReader reader)
{
int PI_count=0, Doc_count=0, comment_count=0, element_count=0, attribute_count=0, text_count=0, whitespace_count=0;