This documentation is archived and is not being maintained.

Code: Reading XML From a File (Visual C#)

Visual Studio .NET 2003

This example uses the XMLTextReader class to extract the element names and text strings from the IntroToVCS.xml file and store the information in a string variable.


System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml");
         string contents = "";
         while (reader.Read()) 
            if (reader.NodeType == System.Xml.XmlNodeType.Element)
               contents += "<"+reader.Name + ">\n";
            if (reader.NodeType == System.Xml.XmlNodeType.Text)
               contents += reader.Value + "\n";

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Replace "c:\\IntroToVCS.xml" with the actual file name.

Note   The XML document must be well-formed.

Robust Programming

The following conditions may cause an exception:

See Also

Code: Writing Class Data to an XML File (Visual C#) | Reading XML with the XmlReader | General Language Example Topics