Microsoft KB Archive/815659

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

Article ID: 815659

Article Last Modified on 11/14/2007

-

APPLIES TO


 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft Visual C++ 2005 Express Edition

-







For a Microsoft Visual C# .NET version of this article, see 307643.



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

IN THIS TASK

 * SUMMARY
 * Requirements
 * How to read XML data from a URL
 * Complete code listing
 * Sample output
 * Troubleshooting
 * REFERENCES



SUMMARY
This article describes how to use the XmlTextReader class to read XML from a URL. The streamed information can come from a variety of sources, such as a byte stream from a server, from a file, or from 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
 * 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 that is named Books.xml. You can create your own Books.xml file, or you can use the sample file that is included with the Microsoft .NET Framework Software Development Kit (SDK) QuickStarts. You can also download Books.xml. To download this file, see the References section of this article.  Copy the Books.xml file to the \Inetpub\Wwwroot folder on your computer. Start Visual Studio .NET or Visual Studio 2005. On the File menu, point to New, and then click Project. In Visual Studio .NET 2002, click Visual C++ Projects under Project Types, and then click Managed C++ Application under Templates.

In Visual Studio .NET 2003, click Visual C++ Projects under Project Types, and then click Console Application (.NET) under Templates.

In Visual C++ 2005, follow these steps:  Under Project Types, click Visual C++. Under Templates, click CLR Console Application.</li></ol>

Note You can proceed to the Complete code listing section or you can continue through these steps to build the application.</li> Add a reference to the System.xml.dll file in the project. For additional information about how to add references to a Managed C++ application project, click the following article number to view the article in the Microsoft Knowledge Base:

310674 HOW TO: Add References to a Managed Visual C++ Project

</li>  Specify the using directive on the System.Xml namespace so that you do not have to qualify the XmlTextReader class declarations later in your code. You must use the using directive before any other declarations. using namespace System::Xml; </li>  Retrieve the XML stream with a URL. Streams are used to provide independence from the device. Therefore, 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 the XmlTextReader class. Add the following code sample to the _tmain function:

Note In Visual C++ 2005, add the following code sample to the main function. String* URLString = &quot;http://localhost/books.xml&quot;; </li>  Create an instance of the XmlTextReader class, and then specify the URL. Typically, the XmlTextReader class is used if you must access the XML as raw data without the overhead of a Document Object Model (DOM). Therefore, the XmlTextReader class 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. Notice that this step shows a basic, outer while loop and that the next two steps describe how to use that loop and how to read the XML. After it is loaded, the XmlTextReader class 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); } </li>  Examine the nodes. To process the XML data, each record has a node type that can be determined from the NodeType property. The Name and the 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. Notice that this example ignores element attributes. while (reader->Read) {   switch (reader->NodeType) {   case XmlNodeType::Element: // The node is an element. Console::Write(&quot;<{0}&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;</{0}&quot;, reader->Name); Console::WriteLine(&quot;>&quot;); break; } } </li>  Examine 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;<{0}&quot;, reader->Name); while (reader->MoveToNextAttribute) // Read the attributes. Console::Write(&quot; {0}='{1}'&quot;, reader->Name, reader->Value); 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;</{0}&quot;, reader->Name); Console::WriteLine(&quot;>&quot;); break; } } </li> Save and build the solution</li> Press CTRL+F5 to run the application.</li></ol>

back to the top

Complete code listing in Visual C++ . NET

 * 1) include &quot;stdafx.h&quot;
 * 2) include <tchar.h>


 * 1) using <mscorlib.dll>
 * 2) using <System.Xml.dll>

using namespace System; using namespace System::Xml;

void _tmain(void) {   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;<{0}&quot;, reader->Name);

while (reader->MoveToNextAttribute) // Read the attributes. Console::Write(&quot; {0}='{1}'&quot;, reader->Name, reader->Value); 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;</{0}&quot;, reader->Name); Console::WriteLine(&quot;>&quot;); break; }   }    Console::ReadLine; } Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile this code sample. To do this, follow these steps:
 * 1) Click Project, and then click ProjectName Properties.

Note ProjectName represents the name of the project.
 * 1) Expand Configuration Properties, and then click General.
 * 2) Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting on the right pane, click Apply, and then click OK.

For more information about the common language runtime support compiler options, visit the following Microsoft Web site:

/clr (common language runtime compilation)

http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx

These steps apply to the entire article.

back to the top

Sample output
Note The Books.xml file that is included with the .NET Framework SDK is slightly different from the file that you can download in the References section of this article. The file that you can download in this article does not have a publicationdate attribute or an ISBN attribute. <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

Troubleshooting
When you run this code, you may receive the following error message:

An unhandled exception of type 'System.Net.WebException' occurred in system.xml.dll

Additional information: The remote server returned an error: (401) Unauthorized.

This may occur if you disable anonymous access to the virtual directory. To resolve this problem, allow anonymous access to the virtual directory, or use the XmlResolver property to specify the credentials that you must have to access the file. The following code is an example: XmlUrlResolver* resolver = new XmlUrlResolver; NetworkCredential* nc = new NetworkCredential(&quot;username&quot;, &quot;password&quot;, &quot;domain&quot;); resolver->Credentials=nc; //CredentialCache::DefaultCredentials if you want to use the current users's credential reader->XmlResolver= resolver; You may also receive the following error message:

An unhandled exception of type 'System.Xml.XmlException' occurred in system.xml.dll Additional information: System error.

You may receive this error message if you use the Books.xml file that you can download in the References section. You receive this error message because the Books.xml file has a white space at the beginning of the file. To fix the problem, open the Books.xml file in a text editor, and then remove the white space.

back to the top