Microsoft KB Archive/307643

= How to read XML data from a URL by using Visual C# =

Article ID: 307643

Article Last Modified on 12/11/2006

-

APPLIES TO


 * Microsoft Visual C# 2005
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q307643





For a Microsoft Visual Basic .NET version of this article, see 301232.

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

IN THIS TASK
SUMMARY
 * Requirements
 * How to Read XML Data from a URL
 * Complete Code Listing
 * Sample Output

REFERENCES



SUMMARY
This step-by-step article shows you how to use the XmlTextReader class to read Extensible Markup Language (XML) from a Uniform Resource Locator (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.

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 or Microsoft Visual Studio 2005

This article assumes that you are familiar with the following topics:
 * XML terminology
 * Creating and reading XML
 * URLs and creating an XML endpoint

back to the top

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. This file is also available for download; refer to the first item in the References section of this article for the download location.  Copy the Books.xml file to the \Inetpub\Wwwroot folder on your computer. Open Visual Studio .NET or Visual Studio 2005. Create a new Visual C# Console Application. You can either proceed to the Complete Code Listing section or continue through these steps to build the application.  Specify the using directive on the System.Xml namespace so that you are not required to qualify the XmlTextReader class declarations later in your code. You must use the using directive before any other declarations. using System.Xml;   Retrieve the XML stream by means of a URL. Streams are used to provide independence from the device; thus, program changes are not required if the source of a stream changes. Declare a constant for the http://localhost/books.xml URL. You will use this constant in the next step with XmlTextReader. Add the following code sample to the Main procedure of the default class: String URLString = &quot; http://localhost/books.xml&quot;;   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 the XML. The XmlTextReader class has different constructors to specify the location of the XML data. The following code creates an instance of an XmlTextReader object and passes the URL to the constructor: XmlTextReader reader = new XmlTextReader (URLString); </li>  Read through the XML. (Note that this step shows a basic, outer &quot;while&quot; loop, and the next two steps describe 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 obtain the next record. The Read method returns false if there are no more records. 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 that 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 example ignores element attributes. 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 the end of the 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. while (reader.Read) {   switch (reader.NodeType) {       case XmlNodeType.Element: // The node is an element. Console.Write(&quot;<&quot; + reader.Name);

while (reader.MoveToNextAttribute) // Read the 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 the end of the element. Console.Write(&quot;</&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; } }                   </li> Build and run your project.</li></ol>

back to the top

Complete Code Listing
using System; using System.Xml;

namespace ReadXMLfromURL {   ///     /// Summary description for Class1. ///    class Class1 {       static void Main(string[] args) {           String URLString = &quot;http://localhost/books.xml&quot;; XmlTextReader reader = new XmlTextReader (URLString); while (reader.Read) {               switch (reader.NodeType) {                   case XmlNodeType.Element: // The node is an element. Console.Write(&quot;<&quot; + reader.Name);

while (reader.MoveToNextAttribute) // Read the 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 the end of the element. Console.Write(&quot;</&quot; + reader.Name); Console.WriteLine(&quot;>&quot;); break; }           }        }    } } back to the top

Sample Output
> <book genre='autobiography' publicationdate='1981' ISBN='1-861003-11-0'> > The Autobiography of Benjamin Franklin > <first-name>> Benjamin </first-name> <last-name>> Franklin </last-name> > 8.99 <book genre='novel' publicationdate='1967' ISBN='0-201-63361-2'>> > The Confidence Man > <first-name>> Herman </first-name> <last-name>> Melville </last-name> > 11.99 <book genre='philosophy' publicationdate='1991' ISBN='1-861001-57-6'>> > The Gorgias > > Plato > 9.99 back to the top