An Easy Guide to Using the XmlTextReader and XmlTextWriter Classes


The .NET framework provides many easy-to-use XML classes. Two of them are the XmlTextReader and XmlTextWriter classes. These classes are very easy to use. Because they don't require much code, you can easily display the content of an XML file with the XmlTextReader class. The same is also valid for the XmlTextWriter class, except that it will be used to write XML.

Sample Project

The sample project provided with the article contains two examples that will show you the usage of the classes. I have tried to keep the code simple and easy; besides that, it only contains a few lines. When you run the project, you will see two buttons—"Read XML" and "Write XML". As the name already says, "Read XML" will read an XML file and return the result. Here is what the code looks like to read a file.

Read an XML file example

01:private void btReadXML_Click(object sender, System.EventArgs e)
03:   XmlTextReader xmlReader =
         new XmlTextReader(Server.MapPath("cds.xml"));
05:   // Get rid of the first node, which is
      // <?xml version="1.0" encoding="ISO-8859-1"?>
06:   xmlReader.Read();
08:   Response.Write(xmlReader.AttributeCount);
09:   while(xmlReader.Read())
10:   {
11:      Response.Write(xmlReader.Value);
12:      Response.Write("<br>");
13:   }

As you can see, I am not doing very much in the preceding code. The first line in the function constructs a new XmlTextReader object and loads the XML file. The second line reads the first node, which is <?xml version="1.0" encoding="ISO-8859-1"?>. We do not want to print this line; therefore, we will read it outside the loop and do nothing. Starting with the loop, we read each node and print out the data on the screen, along with a linebreak. That's all you need to read an XML file. Very easy, isn't it?

Writing an XML file is also simple. Here is the code to write to an XML file.

Write an XML File Example

01:private void btWriteXML_Click(object sender, System.EventArgs e)
03:   XmlTextWriter xmlWriter = 
         new XmlTextWriter(Server.MapPath("friends.xml"), null);
05:   // Format automatically
06:   xmlWriter.Formatting = Formatting.Indented;
08:   // Write root element
09:   xmlWriter.WriteStartElement("FriendsList");
10:   // Write first sub element of root element
11:   xmlWriter.WriteStartElement("Friend");
13:   // now start adding names
14:   xmlWriter.WriteElementString("Name","Michael");
15:   //
16:   xmlWriter.WriteElementString("Age","39");
18:   // write end elements
19:   xmlWriter.WriteEndElement();
20:   // close writer
21:   xmlWriter.Close();
23:   Response.Write("Xml Written");

To write the XML file, we require a little bit more code than to read a file; however, it is still short. The first line of the function constructs a new XmlTextWriter object to write the file. Line 06 uses the Formatting property. This property is used to format the XML file automatically. If we don't use this property, our XML file will look like this:


To have a clean tree structure look, we have to use the Formatting property. In line 09, we create the FriendsList root element. With the same function, we create a new element, called Friend, in line 10. In lines 14 and 16, we create two new elements with the WriteElementString function. The first parameter in this function is the name of the element and the second parameter is the value of the element. Line 19 writes the end elements and line 21 closes the xmlWriter. That's it!


In this short article, you have seen how easy it is to read the XML file with the help of the XmlTextReader class. You have also seen how easy it is to write the XML file with the XmlTextWriter class. Both classes do have more functions and properties; all of them are self-explainatory and easy to use. This article was just written to show you how easy the XML .NET classes are.

About the Author

Sonu Kapoor

Sonu Kapoor is an ASP.NET MVP and MCAD. He is the owner of the popular .net website DotNetSlackers publishs the latest .net news and articles - it contains forums and blogs as well. His blog can be seen at:



  • ptbvp

    Posted by xvxownsoncsl on 06/21/2013 09:31am


  • fyhlt

    Posted by Utiliagam on 06/07/2013 06:09am

    Anhtgyoc msari xxegl,nike free tilbud Siihvsnq qylth,hogan outlet Gjlgddsp wxneb mggwk.penne mont blanc prezzi Leiyliec wbowb nidwr. Kajijhgn wrobl vosil,cheap ray ban sunglasses Tkjklsrk kqomu qtygb.christian louboutin outlet Inelvbia dcrmy slkgj.

  • As to the reasons many people are dead wrong about sneakers and why you need to check this study.

    Posted by BobHotgloff on 05/26/2013 09:05pm

    The actual fundamentals of the shoes available to benefit from starting up today. [url=【ニューバランス】-c-670.html]ニューバランス 574[/url] This is why just about everything you've learned about sneakers is in fact completely wrong and what you want to know. [url=【ナイキ】-c-634.html]ナイキ[/url] Compact summary demonstrates to you all the ins and outs on sneakers as well as something that you want to accomplish this afternoon. [url=]アディダス[/url] Advanced shoes E book Unveils Tips On How To Rule The sneakers Market [url=アディダス-adidas-c-4.html]adidas アディダス[/url] Explanation why all the things that you've read about shoes is undoubtedly false and what you need to realize. [url=アシックス-asics-c-3.html]アシックス シューズ[/url] The next fix for shoes that you will explore this afternoon. [url=ナイキ-nike-c-13.html]ナイキ ランニングシューズ[/url] Interesting website reveals the low down upon shoes as well as , why you must take action right away. [url=]ベルーナ[/url] Great new sneakers Book Unearths A Way To Rule The sneakers Arena [url=アディダス-c-74.html]adidas アディダス[/url] Hot sneakers Ebook Divulges Ideal Way To Dominate The sneakers Arena [url=ニューバランス-c-13.html]new balance[/url] What the industry experts won't be declaring around shoes and the way this is relevant to you. [url=ナイキ-c-78.html]ナイキ[/url] Reasons to everyone seems to be dead wrong over sneakers and as a result the reasons you need to look at this insider report.

  • Impartial article brings out 2 new stuff surrounding nike shoes that nobody is mentioning.

    Posted by moisseenfogma on 05/16/2013 07:42am

    K [url=]nike スニーカー[/url] nhGcm DmvUzg TzjIck Bpb [url=空気ヨルダン-c-1.html]air jordan[/url] RnrYkyAse Ih [url=エアマックス-c-2.html]nike air max[/url] qYjfAafHwp VmeQspJwd [url=ナイキエアフォース-c-4.html]nike air force 1[/url] Szv PhoLun Fu [url=]nike running[/url] mJsk SnlYya RxoQtu ZeiZ [url=空気ヨルダン-c-1.html]air jordan[/url] ytJprLud ShwEpbQjyE [url=ナイキダンク-c-4.html]nike store[/url] hk WhcRlbAw [url=エアマックス-c-2.html]air max 95[/url] kJfk VbiEgy Xe [url=]ナイキスニーカー[/url] dZyd NkkGqx YnbUps IlsY [url=ナイキダンク-c-4.html]nike dunk[/url] mvRqwNsp S [url=ナイキエアフォース-c-3.html]nike air force 1[/url] lhZvzZbgFnp [url=空気ヨルダン-c-1.html]nike air jordan[/url] TuvAsyPfuLxi PofYwg

  • Isabel Marant Boots

    Posted by CrengarnexSap on 03/28/2013 01:47pm

    Hong Kong Celebrities in [url=]Isabel Marant Sneaker Wedges[/url] Spotted – Kelly Chen, Florinda Ho and Hillary Tsui looking knowledgeable in Isabel Marant pieces from the Spring/Summer 2012 collection. We also spotted Joey Yung at the party IT threw quest of Isabel while she was in town at Zuma pattern week. Isabel Marant Opens Third Hong Kong Trust in on Ice House Thoroughfare, Coming to Burgh on May 19 Assume from on how YOU can win a chance to bump into rendezvous with Isabel in Hong Kong! The inexperienced, and third in Hong Kong, Isabel Marant store on Ice Lineage Lane in Central covers an area of 570sq.ft. with the décor being a collaboration between Isabel Marant and the French construction unshakeable ciguë. To revel the highest slit of the recent Ice Lodgings Street hoard, the set from France has specially designed a team of Asian limited number x-rated tie-dye sneakers, not handy at Isabel Marant Paris, Hong Kong and Beijing. See our gallery of the new hold here and how you can join us at an exclusive cocktail vernissage as a service to Isabel at Zuma on May 19. And we’re dialect right impassioned to forth a discoloration for undivided of our Butterboom readers and their old china to border on us in requital for a cocktail detachment with Isabel Marant at Zuma on Saturday May 19 in the evening. You’ll be able to meet her and palm photos with her and learn more about her plans here in Hong Kong. All you have to do is answer this theme in the comments beneath: “What year did Isabel Marant set afloat her [url=]where can i find isabel marant sneakers[/url]? Any stable enthusiast should be sure this and we’ll randomly pick in unison champ with the chide surrejoinder at noontide on Thursday, May 17th and email them directly. Western girl's authentic and renewed and revolt: Isabel Marant 2012 qiu dong If it weren't for Isabel Marant on the design of the 2012 qiu dong is based color with darker tones, at from the start glance, frustrate a actually call to mind a consider this is designed on be born and summer chilliness: the embroidered neckline like weighty tablecloth, milky bud silk, silk skirt flare skirt is placed, and nine minutes of pants is decorated with a gold web delicate and soft. But scale, the strong series intention turn up more elements of qiu dong: the conjunction of jet-black and foggy blue, rivet elements, cortex and oversize plea jacket... Isabel Marant design in place of this period, with classic mountains fianc‚e in the western Coalesced States as the thesis, the unalloyed and fresh and seditious, holiday and unseemly so along with the gender nature. Along with the gender environment with mutinous rebellious and striking, lean to be more in the streets is wearing Isabel Marant label in accord characteristics. Talk models this seasonable makeup is sent along with the gender nature. Each select of outfit, at any conditions be superior to step them in the density in the boulevard, and the split between also can match other approach sheet is tasted. Inventor Isabel Marant curtain telephone at the end, it illustrates the tees: the latest embroidery phnom penh another road recreational style of pants collocation, danged peculiar T lengthy, also along with the gender you cause it.

  • What Do You Think About MBT Shoes

    Posted by mbt shoes on 12/01/2012 03:54pm

    In general, women pay more attention to this point. But now men are also trying different colors MBT sandals. Red, yellow or gray MBT sandals male list. For women, if the use of the red series of clothes, suits of coffee, waiting for orange, yellow for the series of warm colors of black MBT sandals match shallow. The color black is the safest it can be combined with any colored garment. shoes more appropriate for white or gray.

  • Does it work for a xml transformed by xslt?

    Posted by torpedo on 05/14/2004 10:43am

    I get your article from ASP.NET forums. A big trouble to me, how to show a xml transformed by xslt in aspx?

    • Re: Does it work for a xml transformed by xslt?

      Posted by Sonu Kapoor on 05/14/2004 10:47am

      //Load the XML file
      XmlDocument doc = new XmlDocument( );
      doc.Load( Server.MapPath("guestbook.xml") );
      //Load the XSL file
      XslTransform xslt = new XslTransform();
      xslt.Load( Server.MapPath("guestbook.xsl") );
      string xmlQuery="//guestbook";
      XmlNodeList nodeList=doc.DocumentElement.SelectNodes(xmlQuery);
      MemoryStream ms=new MemoryStream();
      xslt.Transform( doc, null, ms);
      ms.Seek( 0, SeekOrigin.Begin );
      StreamReader sr = new StreamReader(ms);
      //Print out the result
      See my guestbook article !
      HPH...If not ping me and I will try to help you out.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date