Is it possible to add attributes with XmlTextWriter?

In this short example we will see whether you can add attributes to the XML file, so that the XML file looks like in the previous examples. The XML file which we used in the previous example looked like this.

XmlTextWriter.xml: (without attributes)

<CategoryList>
  <Category>
    <MainCategory>XML</MainCategory>
    <Description>XML Articles</Description>
    <Active>Yes</Active>
  </Category>
</CategoryList>

If you have read the previous examples then you have recognized that I am using the following XML.

XmlTextWriter.xml: (with attributes)

<CategoryList>
  <Category>
    <MainCategory ID="01">XML</MainCategory>
    <Description>XML Articles</Description>
    <Active>Yes</Active>
  </Category>
</CategoryList>

The key to add the attributes is to use the function WriteAttributeString(). This function takes two parameters: The first one is the attribute name and the second one is the attribute value. However you can not call this function after WriteElementString. The XmlTextWriter class doesn't allow that. If you still do this, you will get the following error message:

Unhandled Exception: System.InvalidOperationException:
Token StartAttribute in state Content would result in an invalid XML document.

So the answer to the question is yes, you can add attributes to the XML document, but the XmlTextWriter class won't create the XML file which we need. The XmlTextWriter will only let you add the attribute after calling WriteStartElement(). The code self contains comments which will explain you the steps to create the XML file.

XmlTextWriterWithAttribute.aspx:

<%@ import namespace="System.Xml" %>
<%@ page language="C#" debug="true"%>

<script runat="server">
void page_load(object sender, System.EventArgs e){
   XmlTextWriter xmlWriter = new XmlTextWriter(Server.MapPath("XmlTextWriterWithAttribute.xml"), null);

    // Format the xml automatically to a tree structure
    xmlWriter.Formatting = Formatting.Indented;

    // Write root element
    xmlWriter.WriteStartElement("CategoryList");
    // Write first sub element of root element
    xmlWriter.WriteStartElement("Category");

    // Write ID Attribute
    // First parameter is the attribute name and the second is the value
    xmlWriter.WriteAttributeString("ID","0");

    // now start adding elements to the Category element
    xmlWriter.WriteElementString("MainCategory","XML");

    // add the 2nd element to the Category element
    xmlWriter.WriteElementString("Description","XML Articles");
    // add the 3rd element to the Category element
    xmlWriter.WriteElementString("Active","Yes");
 
    // write end elements
    xmlWriter.WriteEndElement();
    // close writer
    xmlWriter.Close();

    Response.Write("Xml Written");
}
</script>

Created XML file:

<CategoryList>
  <Category ID="0">
    <MainCategory>XML</MainCategory>
    <Description>XML Articles</Description>
    <Active>Yes</Active>
  </Category>
</CategoryList>

As you can see this is not really what I want. I want the attribute to be added to the MainCategory element. However as mentioned the XmlTextWriter doesn't allow you to do this.

Filed under:

Comments

# Steve said:

have you tried this :

xw.WriteStartElement("MainCategory")

xw.WriteAttributeString("ID", "1234")

xw.WriteString("XML")

xw.WriteEndElement()

gets the right output :

<MainCategory ID="1234">XML</MainCategory>

Wednesday, October 17, 2007 7:09 AM
# fixing leaking showers said:

<a href="www.wpiproject.info/certain46.html">certains dautres non dautres pas</a> certains dautres non dautres pas,<a href="www.wpiproject.info/showers32.html"> showers asian bistro</a>  showers asian bistro,<a href="www.wpiland.info/terrace35.html">who owns doral terrace apts in maryland</a> who owns doral terrace apts in maryland,<a href="www.wpination.info/.../a> sanibel-online,<a href="www.wpiproject.info/showers32.html">naked men in gym showers porn</a> naked men in gym showers porn,<a href="www.pihlz.info/ran52.html">ran horn</a> ran horn,<a href="www.wpisupplies.info/lies17.html">adams tight lies golf</a> adams tight lies golf,<a href="www.wpiproject.info/showers32.html">reynals showers</a> reynals showers,<a href="www.wpiland.info/stormy91.html">private stormy danieals</a> private stormy danieals,<a href="www.revelatevideos.info/thrush12.html">pictures of tongue thrush</a> pictures of tongue thrush,

Tuesday, October 30, 2007 9:08 PM
# maison de diagramme de peinture de kolor said:

<a href="www.superwuz.info/peinture22.html">figure">www.superwuz.info/peinture22.html">figure peinture</a> [url=www.superwuz.info/peinture22.html]figure peinture[/url] figure peinture www.superwuz.info/peinture22.html,<a href="www.officialwuzsupplies.info/vacant38.html">vacant">www.officialwuzsupplies.info/vacant38.html">vacant ames store ohio</a> [url=www.officialwuzsupplies.info/vacant38.html]vacant ames store ohio[/url] vacant ames store ohio www.officialwuzsupplies.info/vacant38.html,<a href="www.glanderiver.info/venue56.html">social">www.glanderiver.info/venue56.html">social events venues in san diego</a> [url=www.glanderiver.info/venue56.html]social events venues in san diego[/url] social events venues in san diego www.glanderiver.info/venue56.html,<a href="www.freewuzstore.info/overlay50.html">overlay">www.freewuzstore.info/overlay50.html">overlay for the underplay</a> [url=www.freewuzstore.info/overlay50.html]overlay for the underplay[/url] overlay for the underplay www.freewuzstore.info/overlay50.html,<a href="www.freewuzstore.info/overlay50.html">pcl form overlay macro</a> [url=www.freewuzstore.info/overlay50.html]pcl form overlay macro[/url] pcl form overlay macro www.freewuzstore.info/overlay50.html,

Thursday, December 20, 2007 3:51 AM
# preisvergleich schweiz said:

<a href="www.habasitio.info/preisvergleich25.html">canon">www.habasitio.info/preisvergleich25.html">canon hv20 preisvergleich</a> [url=www.habasitio.info/preisvergleich25.html]canon hv20 preisvergleich[/url] canon hv20 preisvergleich www.habasitio.info/preisvergleich25.html,<a href="www.suglande.info/edison46.html">edison">www.suglande.info/edison46.html">edison group</a> [url=www.suglande.info/edison46.html]edison group[/url] edison group www.suglande.info/edison46.html,<a href="www.sawuzi.info/boomer17.html">baby">www.sawuzi.info/boomer17.html">baby boomer effect on suburbs</a> [url=www.sawuzi.info/boomer17.html]baby boomer effect on suburbs[/url] baby boomer effect on suburbs www.sawuzi.info/boomer17.html,<a href="www.sawuzi.info/boomer17.html">baby">www.sawuzi.info/boomer17.html">baby boomers 1960</a> [url=www.sawuzi.info/boomer17.html]baby boomers 1960[/url] baby boomers 1960 www.sawuzi.info/boomer17.html,<a href="www.wuznation.info/seizures47.html">identifying">www.wuznation.info/seizures47.html">identifying seizures in cats</a> [url=www.wuznation.info/seizures47.html]identifying seizures in cats[/url] identifying seizures in cats www.wuznation.info/seizures47.html,

Thursday, December 20, 2007 8:58 AM
# how to find the perimeter of a polygon said:

<a href="www.wuzho.info/upskirts36.html">upskirts">www.wuzho.info/upskirts36.html">upskirts gretchen carlson</a> [url=www.wuzho.info/upskirts36.html]upskirts gretchen carlson[/url] upskirts gretchen carlson www.wuzho.info/upskirts36.html,<a href="www.wuzsupplies.info/gwen22.html">gwen">www.wuzsupplies.info/gwen22.html">gwen rogers</a> [url=www.wuzsupplies.info/gwen22.html]gwen rogers[/url] gwen rogers www.wuzsupplies.info/gwen22.html,<a href="www.superwuz.info/polygon67.html">regular">www.superwuz.info/polygon67.html">regular polygon worksheets</a> [url=www.superwuz.info/polygon67.html]regular polygon worksheets[/url] regular polygon worksheets www.superwuz.info/polygon67.html,<a href="www.superwuz.info/polygon67.html">which letters are convex polygons</a> [url=www.superwuz.info/polygon67.html]which letters are convex polygons[/url] which letters are convex polygons www.superwuz.info/polygon67.html,<a href="www.wuzwizard.info/heat26.html">versatec">www.wuzwizard.info/heat26.html">versatec heat pumps</a> [url=www.wuzwizard.info/heat26.html]versatec heat pumps[/url] versatec heat pumps www.wuzwizard.info/heat26.html,

Thursday, December 20, 2007 3:42 PM
# Asina said:

<a href= bestpre.com ></a>

Tuesday, December 02, 2008 2:34 PM
# Breast Pills said:

We Review the Top Breast Enhancing Pills & tell you what really works.

Monday, December 08, 2008 9:28 PM
# Breast Pills said:

We Review the Top Breast Enhancing Pills & tell you what really works.

Saturday, December 20, 2008 3:03 AM
# nick_bocera said:

www.message_varbocco.com

Sunday, December 28, 2008 3:41 PM
# Larcik-sn said:

<a href= http://adultdatingssfinder.com >dating</a>

Sunday, March 01, 2009 12:56 AM
# First pay capital one credit card bill said:

Give somebody the  to a site about the, www.gravatar.com/paycapitalonecredits First pay capital one credit card bill,  0401,

Thursday, March 10, 2011 10:23 AM
# skimpy g string bikini said:

Perfect work, www.gravatar.com/skimpygstringbikinio Real skimpy g string bikini,  86407,

Saturday, March 12, 2011 3:52 AM
# Only one year anniversary gift for boyfriend said:

Best Wishes, www.gravatar.com/oneyearanniversarygi one year anniversary gift for boyfriend,  =-],

Saturday, March 12, 2011 7:08 AM
# Buy i need to know who a phone number belongs too said:

Only, www.gravatar.com/ineedtoknowwhoaphona Buy i need to know who a phone number belongs too,  qtgl,

Saturday, March 12, 2011 8:03 AM
# transparent bikini said:

I want to say thanks!, www.amcharts.com/.../profile.php transparent bikini online,  apawky,

Sunday, March 27, 2011 7:32 AM
# percocet said:

So where it to find?, www.amcharts.com/.../profile.php Discount percocet,  %-O,

Sunday, March 27, 2011 10:15 AM
# weblogs.asp.net said:

204572.. Bang-up :)

Thursday, April 07, 2011 5:22 AM
# fake coach purses online said:

So where it to find, www.crunchyroll.com/.../fakecoachpursesi fake coach purses,  wvoloy,

Tuesday, April 12, 2011 4:36 AM
# louis vuitton purse discount said:

:-), www.crunchyroll.com/.../louisvuittonpursee Buy louis vuitton purse,  =-(,

Wednesday, April 13, 2011 5:26 PM
# last minute gift ideas for you said:

I bookmarked this guestbook., www.crunchyroll.com/.../lastminutegiftideass last minute gift ideas for you,  zuu,

Thursday, April 14, 2011 4:03 AM
# how long does percocet stay in your system for you said:

Best Wishes, www.gravatar.com/howlongdoespercoceta Cheapest how long does percocet stay in your system,  604,

Thursday, April 14, 2011 9:21 AM
# weblogs.asp.net said:

204572.. Awesome :)

Wednesday, June 15, 2011 5:19 AM
# ZeteIntasefam said:

OMG, it is still accepting donations! Fantastic example of a creative fundraising effort that raised $10,000 in 48 hours to build a classroom at the school in Tanzania.

Friday, August 05, 2011 8:49 AM
# блог о путешествиях said:

Hello, look at my website please http://thai-blog.net - блог о путешествиях.

Thursday, September 22, 2011 1:56 PM
# mobic online said:

Hello. And Bye. <a href=http://buy-mobic.net >buy mobic</a> Dont forget to click a link.

Saturday, September 24, 2011 3:51 PM
# Big Lebowski Costume said:

great article. ill share it with my fb friends. keep posting. thx so much

Saturday, October 01, 2011 2:43 PM
# geld verdienen said:

I beackern opak abertausend Poetaster jener, schnell Geld verdienen aufzurichten knistern.

Friday, November 04, 2011 9:49 AM
# .NET Books said:

good answer and question

for more great .NET Books

Wednesday, January 18, 2012 4:53 PM
# momycleTrully said:

You can find evn many more and significantly compensationsMBT boots and boots or boots are not only seen creating brilliant aesthetics, Throughout assist a mechanism. As a consequence grown ups and kids are savoring putting them on. Luxurious artificial buff but fine nylon uppers high the sports plumbing walking look, Consisting of split hallux overlays, Border whipping, Moreover MBT company back overlay.

Tuesday, June 19, 2012 12:38 PM
# momycleTrully said:

Choosing your time, energy when you desire grade clogs, And a lot more, Is an additional to to shop online. With this feature, You will never need to undergo stressed to brew a decision until you are ready. You can look at your choices correctly unless you want to find the most appropriate boot styles in the pocket or your demands.Not knowing talk about oftentimes developed to some substantial a quality prevailing and so are solid, So that they have to genuinely last a long time. Elegance wristbands won't be barely spectacular and also unique, Fortunately they are spouse and children treasures. There are actually a certain amount of solution excellent about passing the gold cut down on with the aid of ages so all people can understand -Granny and the thing that your own woman esteemed and appreciated.

Tuesday, June 19, 2012 1:41 PM
# icon collection said:

 I congratulate, a brilliant idea and it is duly

<a href="www.hpixel.com/.../a>

Monday, September 24, 2012 10:18 AM
# icon downloads said:

<a href="fr.downloadstock.biz/.../Metro-Studio-for-Windows-8.html"> I apologise, but, in my opinion, you commit an error. Let's discuss it. Write to me in PM, we will talk.</a>

Sunday, October 07, 2012 6:51 PM
# icon collection said:

<a href=89.161.134.25/.../viewtopic.php In my opinion you are mistaken. I can defend the position. Write to me in PM, we will discuss.</a>

Sunday, November 04, 2012 5:20 AM
# icons downloads said:

[url=plus-woman.ru/.../flaviacacace] In it something is. Clearly, I thank for the information.[/url]

Sunday, November 04, 2012 2:38 PM
# http://diablopower.tumblr.com/ said:

buydiablo3golds.blogdetik.com/Diablo 3 Gold Cheap

Thursday, November 22, 2012 7:34 PM
# http://pinterest.com/plumberrivers/following/ said:

Is future of plumber promising My Boyfriend is A plumber and i don't think so his future is secured, i want him to change his profession...

Thursday, January 24, 2013 2:59 AM
# Lebron said:

Greetings! Very helpful advice within this post!

It's the little changes which will make the most significant changes. Thanks a lot for sharing!

Sunday, April 21, 2013 10:59 PM

Leave a Comment

(required) 
(required) 
(optional)
(required)