Bind a Nested Xml to a Repeater Control with Container.DataItem
I am still working on my AMS system. If you have read my previous post "Get Attribute Value from XML" then you know how my XML looks like. If not here is it again:
<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
<Category>
<MainCategory ID="3">XML</MainCategory>
<Description>List of XML articles.</Description>
<Active>Yes</Active>
</Category>
</CategoryList>
Now I need to retrieve the ID of the element MainCategory and the value. For that purpose I used a repeater control to bind this xml. It is a simple straight forward code:
DataSet dsCategories = new DataSet();
dsCategories.ReadXml(Server.MapPath("dbase/categories.xml"));
rpDirectory.DataSource = dsCategories;
rpDirectory.DataBind();
Then I used the following Databinder method to retrieve the value first.
<%# DataBinder.Eval(Container.DataItem, "MainCategory") %>
Unfortunaly when finally running the code in the browser, I always got the error message:
System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'MainCategory'.
I could not understand that. My xml file above clearly shows that this element does exist. So where is the error?
After a research on the net I saw a nice post from Kirk Allen, who described a solution for such problems. After reading through his post, I changed my code to the following and it worked like a charm - Thanks Kirk :)
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("dbase/categories.xml"));
XmlNodeList nodes = doc.SelectNodes("CategoryList/Category/MainCategory");
rpDirectory.DataSource = nodes;
rpDirectory.DataBind();
And in the design view of the asp.net page I used this code to retrive the Attribute value:
<%# ((System.Xml.XmlNode)Container.DataItem).Attributes["ID"].Value %>
and to retrive the value of the element I used this code.
<%# ((System.Xml.XmlNode)Container.DataItem).InnerXml %>
Sonu
Thanks to Kirk Allen for this great tip.