Mental Jetsam

By Peter Finch

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" ?>
<news>
 <item id='a1'>
 <title>New Website</title>
 <date>Monday, 7th Feb 2011</date>
 <image>news/website.jpg</image>
 <short>New Development Labs website.</short>
 </item>
 <item id='a2'>
 <title>New Taskbar</title>
 <date>Monday, 207th Dec 2010</date>
 <image>news/taskbar_1.jpg</image>
 <short>Released new taskbar functionality.</short>
 </item>
</news>

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

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

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

<asp:XmlDataSource
  ID="newsDataSource" runat="server"
  DataFile="~/data/news.xml"
  XPath="/news/item[@id='a1']">
</asp:XmlDataSource>

or using the following C# code.

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: