Mental Jetsam

By Peter Finch

Archive for February 14th, 2011

Displaying XML data in .NET

Posted by pcfinch on February 14, 2011

The following is an example of displaying information from a XML document in .NET using an “xmlDataSource” and “DataList”. This is a very simple way to display record base information from an XML data source placed in the application directory like the file below (e.g. “~/data/news.xml”), and it is easy to convert to an “sqlDataSource”, in the future, by replacing the “XPath()” function with “Eval()”.

<?xml version="1.0" encoding="utf-8" ?>
 <item id='a1'>
 <title>New Website</title>
 <date>Monday, 7th Feb 2011</date>
 <short>New Development Labs website.</short>
 <item id='a2'>
 <title>New Taskbar</title>
 <date>Monday, 207th Dec 2010</date>
 <short>Released new taskbar functionality.</short>

Just insert the following code into the C# webform and masterpage.

<asp:XmlDataSource ID="newsDataSource" runat="server" DataFile="~/data/news.xml">
<asp:DataList ID="newsDataList" runat="server" DataSourceID="newsDataSource">
 <img src='images/<%#XPath("image")%>' />
 <a href='details.aspx?id=<%#XPath("@id") %>'>
 <%#XPath("title") %>
 <div><%#XPath("date") %></div>
 <div><%#XPath("short") %></div>

A subset of the XML document can be selected by adding an optional “XPath” attribute to the “xmlDataSource” tag…

  ID="newsDataSource" runat="server"

or using the following C# code.

newsDataSource.XPath = String.Format("/news/item[@id='{0}']", id);

Posted in C#.NET, HTML | Leave a Comment »