Categories: C# .NET

Reading XML in C# .NET with XmlTextReader

In the last post, I’ve shown how to write XML file with XmlTextWriter. Now it is time to also read that XML file.

The thing I want to do is to read XML file with XmlTextReader and add the  attribute value of each node to the listbox.

This is the XML that we are going to use.

<?xml version="1.0"?>
	<profile username="johndoe">
		<name>John Doe</name>
	<profile username="pacman">
		<name>Pac Man</name>

As you can see its pretty much the same as the one we create in this post. The only difference is that I changed “id” with “username” and its value. The reason for doing that is that the values of “username” will make sense when we add the to the listbox. :)

First we need to add the required reference that enables us to work with XML.

using System.Xml;

And then the magic part of the code.

//  Clear WP Setups listbox

//  Load the XML file
XmlTextReader reader = new XmlTextReader("data.xml");

//	Loop over the XML file
while (reader.Read())
	//	Here we check the type of the node, in this case we are looking for element
	if (reader.NodeType == XmlNodeType.Element)
		//	If the element is "profile"
		if (reader.Name == "profile")
			//	Add the attribute value of "username" to the listbox


As you can see, it is really easy to read and get values from XML file with XmlTextReader.

You can also download this example and play around with it.

[download_source_code url=””]


  1. Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about reading XML file using C# code. You made it very simple and understandable. I would like to appreciate you that keep writing. There is also an article which explained very well on this topic and I was found it at searching time. Check it at once too…

  2. XmlDataDocument xmldoc = new XmlDataDocument();
    XmlNodeList xmlnode ;
    int i = 0;
    string str = null;
    FileStream fs = new FileStream(“product.xml”, FileMode.Open, FileAccess.Read);
    xmlnode = xmldoc.GetElementsByTagName(“Product”);

    source… C# XML Reader


Leave a Reply

Your email address will not be published. Required fields are marked *