|
Summary
Example to read a XML file with the system.xml.XmlTextReader class.
There are many .NET classes to read an xml file. Here I will show an example about the XmlTextReader class. The XmlTextReader class is a fast forward only cursor to read xml. This class does not provide any validation for you, so you have to make sure that your XML is valid. If you need to validate your xml you can take a look at the XmlValidatingReader class, which I do not cover here. Let's start with our example.
As you can see there is nothing special in the xml file. It is basically a CategoryList which contains many Categories. Each Category contains three sub elements:
MainCategory:
This contains the name of the category and an unique ID.
Description:
This is the detailed description of the category.
Active:
A status whether the category is active or not. It can contain either Yes or No
Note:
It is important a have a structed and clean XML so that you wont have any problems when reading it with the XmlTextReader. Remember that it does not validate your xml file. To make sure that it is valid, you can open the file in your web browser and it will validate it for you.
First important thing in our code is to import the System.Xml namespace. This namespace provides the necessary XML classes - in our case the XmlTextReader class. In the second line I have set the page language to C# and set the option "debug" to true (just in the case that something doesn't work the way it should).
Finally in the page_load function I have created a new object of the XmlTextReader class and passing the path of the xml file into the constructor. The Server.MapPath function retrieves the full path of the xml file.
The read function then reads the values from the XML file and moves automatically to the next element. It will return true if it has found an element or false if no elements are found.
The first element of the xml file is the xml declaration, which I do not want to display. So, I just read it and do nothing. After that I start a while loop and read the xml file till no elements are left. In the loop I am calling the property Value which will naturally return the value of the XML element. After the loop we then close the XmlReader to clean up any resources.
| Further additional information | |
Updating comments...
Updating comments...
|