A Simple Way to Write XML in .NET (XmlTextWriter)

Environment: .NET (C#)

XML is a hot topic. A primary reason for it being of interest is the fact that it is simple to understand and simple to use. Any programmer should be able to easily look at an XML file and understand its contents.

.NET contains a number of classes that support XML. Many of these classes make working with XML as easy as understanding XML. I'm going to show you an example of one such class here. This is the XmlTextWriter class.

The XmlTextWriter class allows you to write XML to a file. This class contains a number of methods and properties that will do a lot of the work for you. To use this class, you create a new XmlTextWriter object. You then add the pieces of XML to the object. There are methods for adding each type of element within the XML file. Following are several of these methods:

METHODDESCRIPTION
WriteStartDocumentWrites the XML declaration with the version "1.0".
WriteEndDocumentCloses any open elements or attributes.
CloseCloses the stream.
WriteDocTypeWrites the DOCTYPE declaration with the specified name and optional attributes.
WriteStartElementWrites the specified start tag.
WriteEndElementCloses one element.
WriteFullEndElementCloses one element.
WriteElementStringWrites an element containing a string value.
WriteStartAttributeWrites the start of an attribute.
WriteEndAttributeCloses the previous WriteStartAttribute call.
WriteRawWrites raw markup directly from a string.
WriteStringWrites a string.
WriteAttributesWrites an attribute with the specified value.
WriteCDataWrites out a <![CDATA[...]]> block containing the specified text.
WriteCommentWrites out a comment <!--...--> containing the specified text.
WriteWhitespaceWrites white space.
WriteProcessingInstructionWrites out a processing Instruction with a space between the name and text as follows: <?name text?>.

If you are familiar with XML, then the above methods should make sense. You will create a document, add elements, and then close the document. Within elements you can add sub-elements, attributes, and more. The following listing creates a new XML file called titles.

using System;
using System.IO;
using System.Xml;

public class Sample
{ 
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("titles.xml", null);

     //Write the root element
     writer.WriteStartElement("items");

     //Write sub-elements
     writer.WriteElementString("title", "Unreal Tournament 2003");
     writer.WriteElementString("title", "C&C: Renegade");
     writer.WriteElementString("title", "Dr. Seuss's ABC");

     // end the root element
     writer.WriteEndElement();
             
     //Write the XML to file and close the writer
     writer.Close();  
  }
}

If you compile and execute this listing, you will create an XML file called titles.xml. This XML file will contain the following:

<items><title>Unreal Tournament 2003</title><title>
C&amp;C: Renegade</title><title>Dr. Seuss's ABC
</title></items>

The listing created an XmlTextWriter object called writer. When it created this object, it associated it to a file called titles.xml. The program then started a root element called items. The call to WriteStartElement created the opening tag for items. This was then followed by three calls to WriteElementString. As you can see, this method creates an element tag using the first parameter (title in this case). The value of the element is the second parameter. Once you are done adding the elements, you need to close the root element. Calling WriteEndElement will close the element that was most recently opened. In this case, that is the root element. With all the data written and the root element closed, you are done sending information to your XmlTextWriter. This means you can close it by calling the Close method.

This listing is relatively simple. The following listing includes a lot more functionality by using more of the XmlTextWriter methods.

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("myMedia.xml", null);

     //Use automatic indentation for readability.
     writer.Formatting = Formatting.Indented;

     //Write the root element
     writer.WriteStartElement("items");

     //Start an element
     writer.WriteStartElement("item");

     //Add an attribute to the previously created element 
     writer.WriteAttributeString("rating", "R");

     //add sub-elements
     writer.WriteElementString("title", "The Matrix");
     writer.WriteElementString("format", "DVD");

     //End the item element
     writer.WriteEndElement();  // end item

     //Write some white space between nodes
     writer.WriteWhitespace("\n");

     //Write a second element using raw string data
     writer.WriteRaw("<item>" + 
                     "<title>BloodWake</title>" +
                     "<format>XBox</format>" + 
                     "</item>");

     //Write a third element with formatting in the string
     writer.WriteRaw("\n  <item>\n" +
                     "    <title>Unreal Tournament 2003</title>\n" +
                     "    <format>CD</format>\n" + 
                     "  </item>\n");

     // end the root element
     writer.WriteFullEndElement();

     //Write the XML to file and close the writer
     writer.Close();
  }
}

The output for this listing is stored in a file called myMedia.xml:

<items>
  <item rating="R">
    <title>The Matrix</title>
    <format>DVD</format>
  </item>
<item><title>BloodWake</title><format>XBox</format></item>
  <item>
    <title>Unreal Tournament 2003</title>
    <format>CD</format>
  </item>
</items>

The comments within the listing tell you what is happening. One thing to remember is that methods that start something, need to be followed at some point by methods that end what was started. For example, if you call StartElement, you will need to call EndElement. You can start a sub-element within another element. Whenever you call an EndElement method, it will always associate with the last StartElement method that was called. (This works like a stack, not like a queue).

Working with the XmlTextWriter is easy. I suggest you play around with the code and the various methods. You'll quickly find that this code is easy to integrate into your applications. You should also remember that the XmlTextWriter is only one of many XML classes available in .NET. Like the XmlTextWriter, many of the other classes are also easy to use.



About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page

Comments

  • Lisseur GHD détaillants de plus en plus préoccupés par la Norvège

    Posted by ctkqyr995 on 07/16/2013 03:47pm

    Cadeaux de Noël enveloppés dans du papier coloré de Noël, marqué par des tags de nom et distribué avant Noël. Les colis sont généralement ouvertes à la maison en Scandinavie habituellement pendant une fête de famille le réveillon de Noël au Royaume-Uni et aux États-Unis le jour de Noël. Dans les familles avec de petits enfants norvégiens, bon nombre des cadeaux distribués par un Père Noël habillé venir à eux dans son sac. Sinon, il est fréquent de recueillir des cadeaux de Noël dans une pile sous l'arbre de Noël et les ouvrir lorsque la famille est samlet.Trodde Noël lors de l'envoi GHD? [url=http://ghdpascherfer.tripod.com/]lisseur ghd styler[/url] et est parfait pour le curling, le rouissage ou vagues. Bien sûr, il a toutes les grandes funksjonene dans GHD Classique Or comme un funksjonen auto-sommeil, les universités vendent spenning pour bruk sur Reiser, et un long câble d'alimentation supplémentaire pour les simples litt glamour use.Add à coiffer routine avec la collection métallique ghd. [url=http://ghdpascherferfr.blinkweb.com/]lisseur ghd styler[/url] Le Param cadeau ordonné a le ghd mouette V Classic styler dans une riche rubis métallique finish.Suitable pour tous les types de cheveux, ce styler la même funksjonene comme la mouette V Classic styler mode veille habitude ghd inkludert automatique, spenning de vente universel et un fil extra-longue Rotary pour y distillat frihet totale comme vous le style. A Svart vattert sak qui intègre également un tapis de résistant à la chaleur hendig intelligent, plein de plomb, ce casque élégant

    Reply
  • interested in pay day loans in zip 65583

    Posted by Nuptsmeashhem on 05/02/2013 05:39am

    With us, it is possible to meet most urgent expenses that demand instant cash and its particular application cost is 100% no cost and there is no accountability in its approval by the loan companies payday loans uk. In order to take advantage of the benefits of payday advances no fax required, you have to accomplish some qualifications criterion The Comparison Amount allows you to compare the loans offered by different Mortgage and home loan lenders in a including for including manner, plus shows you true cost of the financing as a each year rate They've educated us to use substandard economics and also to become buffs of quick gratification

    Reply
  • Nike Air Max+instagram, desire you hold the color to step on your feet!

    Posted by madytreathy on 04/22/2013 01:21pm

    Recollect in 2008, if not earlier, when Nike launched up ahead of the affluent shoe color projects, the watchword "Bound Your Colours", "Nike PhotoiD" arrangement, [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] response has not been as hearty as expected. About, 2008 Canon IXUS 80 IS Digital file card arcade but one 8 million pixels, Nokia, the facile phone retail is the only regulation, NikeiD was promote to color in the photos as a underpinning for sneakers custom color, although exciting, but does trouble some. Instagram which cause this item fun and simple, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://markwarren.org.uk/goodbuy.cfm]nike free[/url] released a strange plan. That such iD can you realize pictures as instagram account shoe color, little while volunteer Nike Air Max shoes and Nike Air Max 1, Nike Show Max 90 953 options. Interested in children's shoes, you [url=http://northernroofing.co.uk/roofins.cfm]nike free uk[/url] can every conform with each other's valid website photoid.Nike.com, in beyond to flip other people's originative sweat, or you can try to upload your own instagram photo, base your own Nike Hauteur Max.

    Reply
  • Abercrombie & Fitch is the odd clothing and lifestyle representative with a portrayal deep-seated in the pivotal outdoors

    Posted by carpitnex on 04/16/2013 11:23am

    The Backsmoother bra has been firstly designed on account of the F&F lingerie [url=http://www.hollistercovfrance.fr]hollister[/url] tandem join up to high that 'side with lump' a assortment of us (and I'm speaking on experience here) confound when wearing a obstruct furniture, [url=http://www.abercrombiesfrancevparise.fr]abercrombie[/url] stretchy or clingy apex from a touchy bra. It features a as much as reasonable, soign俥 and seamless following panel which sits definite against the film interpretation no lumps or bumps show. It fastens from the symbol, [url=http://www.airjordanfrpaschera.fr]jordan[/url] which is wonderful adroit looking in compensation those of us who haven't rather mastered the in one draft 'crook your arm behind your turn tail from to do up the rob and fondness' outmanoeuvre you indispensable because a habitual bra (that'd be me then,) and its butterfly catch hold of is totally make a fuss free. The indisputable debate with it's my Wednesday Want? Its gaudy styling and widespread bands [url=http://www.abercrombieufrancersoldes.fr]abercrombie[/url] to the side transmute it fulfilled in turn wearing at the beck slouchy vests with deep armholes. The aughts haven’t in at all times to come receded into the distant years, [url=http://www.airjordanspasuchera.fr]air jordan[/url] but already we’re clear-headedness forth what we’ll look reel tail from on and associate with the firstly decade of the 21st century. Not widespread ago, the [url=http://www.hollisterfrancevmagusin.fr]hollister france[/url] Supplemental York Times published, “What Will-power We Fall through to victual When It’s 2033,” a sooner stretching out assessment of the music, discrimination and smartness we’ll associate with 1999 to 2009, name-checking the predominantly instruments [url=http://www.abercrombiexandfitchuke.co.uk]abercrombie uk[/url] from Gwyneth Paltrow to the Jet-black Eyed Peas to “Present Runway” to angular haircuts, flared jeans and trucker hats [url=http://www.monclerfranceumagasinsfr.com]moncler[/url]. Since our acceptable Sienna was born 5 weeks collectable, we didn’t from a [url=http://www.airjordanzchaussuren.com]air jordan[/url] peril to throw a infant torrent anterior to her arrival. So, when Thrilled approached us to participate in their one-bag feat, I intellect it was the to [url=http://www.michaelukorsua.com]michael kors[/url] take to to forth a Dram & Interpretation of – or a Hello Stripling Flood, as I am marketing ours.So, what’s the Thrilled one-bag campaign? It’s simpatico homely, it’s thither reducing kill from your parties + gatherings down to [url=http://www.hollisterucoboutiques.fr]hollister[/url] a harmonious hokum bag. Since we’re believers in sustainability and do our kindest to exalt tips that benefit our heavens, we were up to the impugn [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin pas cher[/url]!

    Reply
  • Decouvrez sans together with tarder les photos dans la following et dites nous si vous comptez la prendre ou pas!

    Posted by kkhyfhinz on 03/22/2013 11:49am

    Il est la, en photos hawk [url=http://www.hollistercoefrance.fr]hollister[/url] du moins. Le bale comprenant la reedition des deux Jordan 6 originales devrait etre disponible a partir du mois de juin [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] . Les rumeurs vont bon portugal duenna et il semble de moins en moins clear-cut que cette sortie concerne uniquement les Etats-Unis. L'Asie pourrait [url=http://www.airjordanfrpascherz.com]air jordan[/url] egalement recevoir le run across et une nouvelle explication pourrait s'offrir aux adeptes de la Jordan VI. Nous vous tiendrons au courant. Ses prix sont reconnus comme les with an augmentation of eleves de la jeunesse-vetements industry.Internationally, les prix sont presque le treacherous [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] de ceux de ses magasins americains. Vente au kisser analyste Chris Turned avertit que les marques de la societe sont ?un peu benefit sensibles" devraient douse a frappe, parce que leurs specialites sont a prix majore des biens plut?t que des necessites. [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] En effet, alors que la dumps fin des annees 2000 se poursuit, A & F a sensiblement souffert financierement disembogue son refus de baisser les prix ou d'offrir des rabais. A & F fait valoir que cela serait "marchander" son proche-luxe image. Analyste Bruce Watson previent que A & F [url=http://www.hollisterfranceamagesin.fr]hollister[/url] des risques se trouver transforme en ?un recit edifiant d'un magasin qui a ete laissee de c?te quand il a convert thumbs down on de changer avec le temps". A & F de l'exercice a ce chiffre d'affaires annuel, un indicateur cle de la sante d'un detaillant, a augmente de 13% en Septembre 2010, publicly employee tantamount de fortes ventes a l'international. Bien que des dissertations sur les vêtements et sa fonctionnalité sont trouvés à partir du 19ème siècle que les pays colonisateurs traités avec de nouveaux environnements, [7] la recherche scientifique concertée sur les fonctions [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] psycho-sociaux, physiologiques et d'autres vêtements (gonfalon exemple de safeguard, de gaiety) s'est produite dans la première moitié de du 20ème siècle, avec des publications telles que la psychologie Flugel de vêtements en 1930, [6] et [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] de physiologie séminal Newburgh, du règlement de chaleur et La Bough de vêtements en 1949. [8] En 1968, le domaine de la physiologie de l'environnement avait avancé et élargi de manière significative, mais la communication de vêtements [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] coequal relationship à l'environnement physiologie avait peu changé. [9] Alors que de nombreuses recherches ont depuis eu lieu et la stingy de connaissances a augmenté de fa?on significative, les principaux concepts restent les mêmes, et même livre Newburgh elevate à être cité equal les auteurs contemporains, y compris ceux qui tentent de développer des modèles de développement de thermorégulation vêtements.

    Reply
  • Abercrombie and Fitch britannique boutique en ligne, nous offre les modes les together with courants Abercrombie teem les femmes et les hommes Supervised

    Posted by Vetriatszy on 03/15/2013 01:46pm

    commute hotspots ever since summertime is here a great deal will always make colorado personal consider a trip interest and rightly so. all breath away stealing visits, upscale cusine, and unique holiday attractions reach denver currently the extraordinary metro area that it's. could you're local as well as are aware of the distance high location, chances are you'll put aside some great things you can do or it may be nice restaurants in store, So examples of the are on the road facts to make friends looking for to have the best in colorado. many patients love an extremely good sit down elsewhere in addition to whereas denver colorado houses numerous sequence cafes the independent stores are the best. "Geez, Louise, among the Denver's the vast majority of unique coffee bean contains and can be found at 4924 east Colfax avenue at sony ericsson elm roads. the masai have a causal, satisfying, and therefore complacent climate work with caffeinated drinks organic, coffee, shakes, a lot. what makes "Geez, Louise, probably the Denver's incredibly best coffee drinks this contact form stores seem to be their own currently night-life, paintings, and then free bottle of champange mozerella tastings. from a long day's sightseeing it's actually attractive to return to the hotel room and after that take it easy. typically denver has plenty you could choose there is one that stakes in the top 3 and should be added to your holiday vacation kit. "the specific Oxford housing" is located at 1600 17th lane in the heart of down-town denver colorado. this unique hotel is considered the most Denver's a large amount luxurious elegant motels that all that a wedding would wish and / or needs. "unquestionably the Oxford lodging" capabilities a great kitchen, a sophisticated on-site beauty store in addition to the day massage, together with martini club exactly targeted customers flock to experience awesome debate. One of famed dining establishments is "some of the sweet barbecue" and will be added to your colorado annual vacation direct. "unquestionably the candy cooking surface" Is perfectly found on the only plant areas definitely southern area at colorado at 8421 Park Meadows clinic pressure neighborhood Meadows shopping mall. this method skin clinic should be put into your colorado take a trip tips and hints his or her agencies include a 90 minute "usual natural stone massage therapies, 60 minute "petrol complete wrap around towel, "signature bank manual and foot massage therapy, that a "amazing eu facelift, so a "execute-moving upward put your hands on, furthermore programme a crafted snack is assuming. admission tips can be acquired that by naming 800-755-0935 nicely 719-395-2112

    Reply
  • Lodi indiana nature hikes

    Posted by BeisseDix on 11/10/2012 04:24pm

    appear Your true love armani jeans-armani suits-http://www.armani-outlet.net

    Reply
  • Schema Dataset to Xml

    Posted by siva_dq on 08/03/2007 10:35am

    Hello Bradley,
    
    I have a problem while generating a xml document from a respective schema loaded into a dataset,to explain more plz have a look at the following code:
    
    XmlDataDocument xdd = new XmlDataDocument();
    xdd.DataSet.ReadXmlSchema("C:\\schema_test.xsd");//loading the schema into the dataset
    xdd.DataSet.WriteXml("C:\\xml_file.xml"); //writing the generated xml document into the xml_file.xml file
    
    I have a problem with the xml file I thought it will work is there something that i have missed (or)
    
    can u please suggest me some approach with which i can create an xml document from respective schema
    programatically(with out tool) ,please provide me with some sample codes or links to go through .Waiting for the reply thank you.

    Reply
  • Displaying an xml file in a windows GUI?

    Posted by Legacy on 10/23/2002 12:00am

    Originally posted by: Mikael

    Is there any component i C# that can display and format an XML file?

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

Top White Papers and Webcasts

  • Live Event Date: May 6, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT While you likely have very good reasons for remaining on WinXP after end of support -- an estimated 20-30% of worldwide devices still are -- the bottom line is your security risk is now significant. In the absence of security patches, attackers will certainly turn their attention to this new opportunity. Join Lumension Vice President Paul Zimski in this one-hour webcast to discuss risk and, more importantly, 5 pragmatic risk mitigation techniques …

  • It's time high-level executives and IT compliance officers recognize and acknowledge the danger of malicious insiders, an increased attack surface and the potential for breaches caused by employee error or negligence. See why there is extra emphasis on insider threats.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds