How to: Read XML from a File
This example uses the XmlTextReader class to extract the element names and text strings from a sample file and store the information in a string variable.
Example
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("c:\\IntroToVCS.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.NodeType == System.Xml.XmlNodeType.Element)
contents += "<"+reader.Name + ">\n";
if (reader.NodeType == System.Xml.XmlNodeType.Text)
contents += reader.Value + "\n";
}
System.Console.Write(contents);
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 condition(s) may cause an exception:
- The path name may be too long.
See Also
Concepts
Designing a User Interface in Visual C#