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"?>
<users>
	<profile username="johndoe">
		<name>John Doe</name>
		<gender>male</gender>
		<age>99</age>
	</profile>
	<profile username="pacman">
		<name>Pac Man</name>
		<gender>male</gender>
		<age>11</age>
	</profile>
</users>


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
lbUsernames.Items.Clear();

//  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
			lbUsernames.Items.Add(reader.GetAttribute("username"));
		}
	}
}

reader.Close();

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=”http://www.lessthanweb.com/demo/reading-xml-in-c-net-with-xmltextreader/XmlTextReaderExample.zip”]

2 Comments

  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…

    http://mindstick.com/Articles/851bfc02-9c84-41c4-a3ca-d83b5fd0adf2/?How%20to%20read%20data%20from%20XML%20file%20in%20C%20Sharp

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

    source… C# XML Reader

    Elv.

Leave a Reply

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