I am trying to create a bulleted list and use an xml file (Kategoriler.xml
) as data source. Here is my xml
code:
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
And design of page:
<asp:BulletedList ID="BulletedList2" runat="server" BulletStyle="Numbered" DataSourceID="XmlDataSource1">
</asp:BulletedList>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Kategoriler.xml"></asp:XmlDataSource>
When I run the code i see a list like this:
1.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
2.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
3.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
4.System.Web.UI.WebControls.XmlDataSourceNodeDescriptor
I don't know what I am doing wrong. Thanks for your time.
You have to specify the DataTextField
& DataValueField
properties in your BulletedList
:-
<asp:BulletedList ID="BulletedList2" runat="server" BulletStyle="Numbered"
DataSourceID="XmlDataSource1" DataTextField="author" DataValueField="year" >
</asp:BulletedList>
Update:
@Michael is correct XmlDataSource
does not work with values of xml nodes but only with attributes, so either you will have to modify your XML like this:-
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author name="Giada De Laurentiis" year="2005"></author>
<year></year>
<price>30.00</price>
</book>
</bookstore>
Then, you will have to specify the XPath
attribute like this:-
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Kategoriler.xml"
XPath="/bookstore/book/author"></asp:XmlDataSource>
Then, change your BulletedList attributes accordingly:-
DataTextField="name" DataValueField="year"
But, in reality you probably won't be able to change your XML itself so you can read this XML in code behind and then programmatically bind your BulletedList.
Update 2:
As I said it's not practical to change your XML file according to the XMLDataSource
behavior you can alternatively use LINQ-to-XML
to query your XML file and bind it like this:-
XDocument xdoc = XDocument.Load(@"YourXMLFilePath");
var XMLdata = xdoc.Descendants("book")
//Optional Filter
.Where(x => (string)x.Attribute("category") == "cooking")
.Select(x => new
{
AuthorName = (string)x.Element("author"),
Year = (string)x.Element("year")
});
Finally, you can bind the data like this:-
BulletedList2.DataSource = XMLdata;
BulletedList2.DataValueField = "Year";
BulletedList2.DataTextField = "AuthorName";
BulletedList2.DataBind();