Microsoft KB Archive/815658

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

Article ID: 815658

Article Last Modified on 5/13/2007

-

APPLIES TO


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

-







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



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

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

System.xml

IN THIS TASK

 * SUMMARY
 * Requirements
 * Read the XML data from a file
 * View the complete code listing
 * View the sample output
 * Troubleshooting
 * REFERENCES



SUMMARY
This article describes how to use the XmlTextReader class to read the XML data from a file. The XmlTextReader class provides direct parsing and tokenizing of the XML data. The XmlTextReader class also implements the XML 1.0 specification, in addition to the namespaces, in the XML specification that is defined by the World Wide Web Consortium (W3C). This article describes how to do fast, tokenized stream access to the XML data instead of using an object model, such as the XML Document Object Model (DOM).

back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * XML terminology
 * How to create and how to read an XML file

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Studio .NET
 * Microsoft Visual Studio 2005

back to the top

Read the XML data from a file
The example in this article 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 Software Development Kit (SDK) QuickStarts. The Books.xml file is also available for download from the Microsoft Download Center:

Download Books.xml now

You must copy the Books.xml file to the project folder.

To read the XML data from a file, follow these steps:  Start Visual Studio .NET 2002, Visual Studio .NET 2003, or Visual Studio 2005. On the File menu, point to New, and then click Project.

The New Project dialog box appears. Under Project Types, click Visual C++ Projects.

Note In Visual Studio 2005, Visual C++ Projects is changed to Visual C++.

 Under Templates, click Managed C++ Application if you are using Visual Studio .NET 2002.

Under Templates, click Console Application (.NET) if you are using Visual Studio .NET 2003.

Under Templates, click CLR Console Application if you are using Visual Studio 2005. In the Name box, type Q815658, and then click OK. Add a reference to System.xml.dll in the project. For additional information about how to add references to a managed Visual C++ 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 in the System::Xml namespace as follows: using namespace System::Xml; You do this 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. </li>  Create an instance of the XmlTextReader object. Populate the XmlTextReader object with the .xml file.

Typically, the XmlTextReader class is used if you have to access the raw XML data without the overhead of the DOM. Therefore, the XmlTextReader class provides a faster way to read the XML data. The XmlTextReader class has different constructors that specify the location of the XML data.

The following code creates an instance of the XmlTextReader class and then loads the Books.xml file. Add the following code to the _tmain function: XmlTextReader* reader = new XmlTextReader (&quot;books.xml&quot;); Note In Visual C++ 2005, the _tmain function is changed to the main function. </li>  Read through the XML data.

Note This step demonstrates an outer while loop. The two steps that follow this step demonstrate how to use the while loop to read the XML data.

After you create the XmlTextReader object, use the Read method to read the XML data.

The Read method continues to sequentially move through the .xml file until the Read method reaches the end of the file. When the Read method reaches the end of the file, the Read method returns false. 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 property and the Value property return the following information for the current node or for the current record: <ul> The node name that is the element name and the attribute name.</li> The node value that is the node text.</li></ul>

The NodeType enumeration determines the node type. The following code sample displays the name of the elements and the document type. The following code sample 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 the element node types. The MovetoNextAttribute method sequentially moves 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 the solution. Build the solution.</li> Press CTRL+F5 to run the sample application.</li></ol>

back to the top

View the complete code listing in Visual Studio .NET 2002 or in Visual Studio .NET 2003

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

using namespace System; using namespace System::Xml; void _tmain(void) {   XmlTextReader* reader = new XmlTextReader (&quot;books.xml&quot;);
 * 1) using <mscorlib.dll>
 * 2) using <System.xml.dll>

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 the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
 * 1) Click Project, and then click   Properties.

Note  is a placeholder for 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 in the right pane, click Apply, and then click OK.

For more information about the common language runtime support compiler option, 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 whole article.

back to the top

View the sample output
Note The Books.xml file that is included with the .NET SDK QuickStarts has two differences from the Books.xml file from the download link that is mentioned in the &quot;Read the XML data from a file&quot; section.
 * The Books.xml file from the download link does not have the publicationdate attribute.
 * The Books.xml file from the download link does not have the 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 the sample application, you may 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 from the download link that is mentioned in the &quot;Read the XML data from a file&quot; section. This problem may occur if the Books.xml file has a white space at the beginning of the file. To resolve this problem, open the Books.xml file by using a text editor and then remove the white space.

back to the top

<div class="references_section">