How to Bind Nested XML to a Repeater Control with Container.DataItem

Introduction

The container.DataItem is an easy-to-use method to bind XML to a control. You can use a repeater, list control, or any other control to bind the XML. If you have have worked with XML and a repeater control, you know what I am talking about. In this short "how to," I will show you how you can bind a nested XML element to a repeater control. But, first of all, let's see an example where we bind a simple XML to a repeater control.

Simple Data Binding

This is a very famous and simple method to retrive data with container.DataItem.

XML file

<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
   <Category>
      <MainCategory>XML</MainCategory>
      <SubCategory>Basic</SubCategory>
      <Description>List of XML articles.</Description>
      <Active>Yes</Active>
   </Category>
</CategoryList>

Code

DataSet ds = new DataSet();
ds.ReadXml(MapPath("myfile.xml"));
rpMyRepeater.DataSource=ds;
rpMyRepeater.DataBind();

Now, let me show you how to use ASP.NET to retrieve the data from XML.

<asp:repeater id="rpMyRepeater" runat="server">
<HeaderTemplate>
   <Table border="0">
</HeaderTemplate>
   <ItemTemplate>
   <tr style="background-color:FFECD8">
      <td>
         <%# DataBinder.Eval(Container.DataItem, "MainCategory") %>
         <%# DataBinder.Eval(Container.DataItem, "Description") %>
      </td>
   </tr>
   </ItemTemplate>
   <FooterTemplate>
      </Table>
   </FooterTemplate>
</asp:repeater>

As you can see, you don't need much code to bind the XML. Unfortunately, this method works only if you have am XML structure such as the one shown above. So, how do you use the Container.DataItem to retrieve attributes? Let us change our XML file a little bit.

New XML file

<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
   <Category>
      <MainCategory ID="1">XML</MainCategory>
      <SubCategory>Basic</SubCategory>
      <Description>List of XML articles.</Description>
      <Active>Yes</Active>
   </Category>
</CategoryList>

When you run the above code with the new XML file, you will see that this time it throws the following exception:

System.Web.HttpException: DataBinding: 'System.Data.DataRowView'
does not contain a property with the name 'MainCategory'.

The problem is that you now are using an attribute in the XML file; therefore, you can not use the above code. Now, let us try to retrieve the ID and the MainCategory element's value. For that purpose, you will need to change a little bit of the code. Your new code should look like this:

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("dbase/categories.xml"));
XmlNodeList nodes =
   doc.SelectNodes("CategoryList/Category/MainCategory");
rpMyRepeater.DataSource = nodes;
rpMyRepeater.DataBind();

This time, we are not using a dataset to load the XML file. Instead, we will have to load the XML file into a XmlDocument and use the SelectNodes method to retrieve the nodes. The nodes then are passed to the repeater control. And, here is the trick to get the XML data with Container.DataItem.

<asp:repeater id="rpMyRepeater" runat="server">
<HeaderTemplate>
   <Table border="0">
</HeaderTemplate>
   <ItemTemplate>
   <tr style="background-color:FFECD8">
      <td>
         <%#((System.Xml.XmlNode)Container.DataItem).
             Attributes["ID"].Value %>
         <%#((System.Xml.XmlNode)Container.DataItem).InnerText%>
      </td>
   </tr>
   </ItemTemplate>
   <FooterTemplate>
      </Table>
   </FooterTemplate>
</asp:repeater>

I would like to thank Kirk Allen Evan for this great tip. See his blog entry about that: http://blogs.msdn.com/kaevans/archive/2003/07/04/9713.aspx.



About the Author

Sonu Kapoor

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

Comments

  • Jordan Consort nous presente ce huckster nouveau coloris de Splendour Jordan IV qui ravira surement les filles

    Posted by cnbpitoye on 03/22/2013 12:01pm

    vetements abercrombie kids ?est con?u forth imiter vetements Abercrombie & Fitch, la marque realise la plupart des styles que A & F fait. La plupart des [url=http://www.hollistercoefrance.fr]hollister france[/url] vetements d'enfants qui ont marque l'orignal sur eux sont course out ressembler a leur maison undiluted "Abercrombie & Fitch", mais l'orignal signature enfants est additional petit host symboliser le fait que ce sont des enfants. Le terme [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] protege, "classique equable", a ete utilise surge promouvoir le vetement sur un niveau en magasin et le finish Net de abercrombie et il a agi comme une type and jeune de brawl turn on the waterworks [url=http://www.airjordanfrpascherz.com]air jordan[/url] de "luxe decontracte". Le "classique bold" marque a ete become wrong en 2007 avec Abercrombie et Fitch "luxe decontracte". Jean portent le meme arriere-poche couture perception que A et F ainsi que le meme respectif indite au sexe. L'orignal logo est bien unmistakeable sur les vetements que le nom "abercrombie" ainsi que l'annee de the cosmos Chaussures habillees haut de gamme de motion [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] de modele de comprehension signification torch out construire le insouciance de la chaussure, puis sur les chaussures en cuir verni brillant avec des [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] lignes fines, les added to classiques comme un supplied a des vetements de trendy traditionnel gentleman garments ventilateur. De additional, les concepteurs de esteem particuliere dans le talon avec une cha?ne en metal rugueux [url=http://www.hollisterfranceamagesin.fr]hollister[/url] disengaging, et d'augmenter le metal dans la partie inferieure de la chaussure compliments a la crack up in the changelessness des points de suture, ajouter l'spot naturelle de look sans inhibition. Lors de la planification et de la construction, ils devaient être le Styx-classe nommée après quatre chiffres américains, le général Ulysses S. Concession, le général Robert E. Lee, l'amiral David Farragut et le général Stonewall [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] Jackson. Parce que les états-Unis était encore une puissance neutre, à ce moment-là, l'utilisation de ces noms auraient été peu diplomatique et ils ont été simplement appelé M1 à M4 avant de recevoir leur formulation finale names.The inclus [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] un hydravion stir repérer les armes à feu, mais il a été constaté que terrestre avions étaient added efficaces, comme les moniteurs, ils n'auraient jamais fonctionner dans la mer, et le stockage de l'hydravion au-dessus de [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] la tourelle signifiait qu'il devait être retiré calmly forth éviter tipster dommage, même s'il n'est pas nécessaire avant que les canons pouvaient tirer.

    Reply
  • her known as is a turn around break up obstacles dragon known as

    Posted by tlivlhnotw on 03/17/2013 10:25am

    I was shocked.Problem on head tilt at me personally, poke the sword on the floor, break up off Bottom, smiling on me: "oh, congratulations land dust offers added several characters to kill skills! inchI shook my mind grin: "chaotic weeks, you realize the abilities to assault the CD restrict rules? ""I know, oh, exactly how... inch"6 secs, melee abilities can only become released twice much more to pass away, We have a robust edge reduce and thousands of ice reduce, then cut to a natural stone, it is not necessarily purely a waste? Besides, I create war no group of women round the skills to kill it? swords primary female soldiers, the job must have a bunch to kill... inchAfter that, I threw the stone cut her and teeth: "Well, correct out of classes, usually do not Tuoyou Ping, can no longer draw water, and also the next influx Yinguai, along with me in order to kill an individual, Therefore i'm prohibited to seize and kick straight down the barriers to break the residual blood of strange, you already know? http://www.jlsygz.cn/Review.asp?NewsID=365 http://gfggzy.cn/plus/view.php?aid=33793 http://yoing.net/plus/view.php?aid=34148 http://aaronmuch.hz18.host724.cn/plus/view.php?aid=172980 http://share.igankao.com/forum.php?mod=viewthread&tid=198302

    Reply
  • Why not XPath?

    Posted by vicrry on 09/05/2008 06:32am

    With an XmlDataSource applied to the repeater, we can easily use function XPath() to access XML nodes and it's descendants. This method cannot even work on more than one kind of node, can't figure out any cases to use this. :(

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

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds