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
topRequirements
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 topHow 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.
Note You can proceed to the Complete
code listing section or you can continue through these steps to
build the application. - 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
- 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;
- 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 = "http://localhost/books.xml";
- 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);
- 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);
}
- 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("<{0}", reader->Name);
Console::WriteLine(">");
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("</{0}", reader->Name);
Console::WriteLine(">");
break;
}
}
- 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("<{0}", reader->Name);
while (reader->MoveToNextAttribute()) // Read the attributes.
Console::Write(" {0}='{1}'", reader->Name, reader->Value);
Console::WriteLine(">");
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("</{0}", reader->Name);
Console::WriteLine(">");
break;
}
}
- Save and build the solution
- Press CTRL+F5 to run the application.
back to the
topComplete code listing in Visual C++ . NET
#include "stdafx.h"
#include <tchar.h>
#using <mscorlib.dll>
#using <System.Xml.dll>
using namespace System;
using namespace System::Xml;
void _tmain(void)
{
String *URLString = "http://localhost/books.xml";
XmlTextReader *reader = new XmlTextReader (URLString);
while (reader->Read())
{
switch (reader->NodeType)
{
case XmlNodeType::Element: // The node is an element.
Console::Write("<{0}", reader->Name);
while (reader->MoveToNextAttribute()) // Read the attributes.
Console::Write(" {0}='{1}'", reader->Name, reader->Value);
Console::WriteLine(">");
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("</{0}", reader->Name);
Console::WriteLine(">");
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:
- Click Project, and then click ProjectName Properties.
Note ProjectName represents the name of the project. - Expand Configuration Properties, and then click General.
- 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:
These steps apply to the entire article.
back to the topSample 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.
<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>
back to the topTroubleshooting
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("username", "password", "domain");
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
topREFERENCES
The
following file is available for download from the Microsoft Download
Center:
Download
the Books.xml package now. For additional information about how to download Microsoft Support
files, click the following article number to view the article in the Microsoft
Knowledge Base:
119591 How to Obtain Microsoft Support Files from Online Services
Microsoft scanned this file for viruses. Microsoft used the most
current virus-detection software that was available on the date that the file
was posted. The file is stored on security-enhanced servers that help to
prevent any unauthorized changes to the file.
For more information about the
XmlReader class, visit the following Microsoft Developer Network (MSDN) Web
site:
For more information about how to use the
XmlReader class to read XML data, visit the following MSDN Web site:
back to the
top