Click here to Skip to main content
Click here to Skip to main content

Introduction to XMLDataSource control in ASP.NET 2.0

By , 4 Jul 2005
 

Introduction

XML is an important format for storing and retrieving data on the web and the reason is it can be moved between firewalls. We see many websites with RSS and XML output. Many visitors use them to save their time and increase their speed for viewing their favorite websites and web logs. As a developer you should know that Visual Studio .NET 2005 helps you to work with XML data with its new XMLDataSource control.

Using this new control you can insert, delete and update XML data easily in minimum amount of time. In this article I'm going to show you how to use this new control and describe its common properties and features. I'll try to show these features in ASP.NET because this new control is more applicable on the web.

Local XML file

First we need to create this XML file before using our new control: (XMLFile.xml)

<?xml version="1.0" encoding="utf-8" ?>
<IranHistoricalPlaces>
 <Place name="Taghe Bostan">
  <City>Kermanshah</City>
  <Antiquity>2000</Antiquity>
 </Place>
 <Place name="Persepolis">
  <City>Shiraz</City>
  <Antiquity>2500</Antiquity>
 </Place>
</IranHistoricalPlaces>

Now I use the following code to show my XML file data in a Repeater control:

<asp:Repeater ID="Repeater" runat="server" DataSourceID="XmlDataSource">
 <ItemTemplate>
    <Strong><%# XPath("@name") %><br /></Strong>
    <%#XPath("City")%><br />
    <%#XPath("Antiquity")%><br />
 </ItemTemplate>
</asp:Repeater>
<asp:XmlDataSource ID="XmlDataSource" runat="server" DataFile="~/XMLFile.xml" 
 XPath="IranHistoricalPlaces/Place">
</asp:XmlDataSource>

In the above code, first I add the XMLDataSource control from the toolbox to my form then I set its DataFile property to the XML file's relative address (~/XMLFile.xml) and its XPath property to "IranHistoricalPlaces/Place". The last one points to our desired level of XML file that we want to work with its nodes.

Now I try to set up my Repeater control for using this XMLDataSource. First set the DataSourceID property to "XMLDataSource" then try to configure this control to show your desired values from XML nodes. I don't want to focus on the formatting codes at this moment. I have used XPath("Nodename") to load my desired data between ItemTemplate tags. If it's an attribute that I want to load into my page I must use @ with its name for my XPath parameter and if it is an element I send its name directly to XPath.

The final result is shown in the following figure:

XML file on the web

We aren't limited to using local XML files. We can use XML files on the web to show in our Web Forms (and it's the major application of this new data control).

Assume that you want to use your favorite RSS in your Web Form. I'll show you how you can do this.

Insert another XMLDataSource control with a DataList control in your Web Form (I prefer using another Web Form). Set the Datafile property to your XML file URL (I used my RSS URL here) then set the DataSourceID property of the DataList control to "XMLDataSource" as shown below:

<asp:XmlDataSource ID="XmlDataSource" DataFile="http://nayyeri.net/rss.aspx" 
XPath="rss/channel/item" runat="server"></asp:XmlDataSource>
<asp:DataList ID="DataList" runat="server" DataSourceID="XmlDataSource">
 <ItemTemplate>
     <font face="tahoma" size="6"><Strong><%#XPath("title")%><br />
     </Strong></font>
     <%#XPath("description")%><br />
     <font color="navy"><i><%#XPath("pubDate")%><br /></i></font>
 </ItemTemplate>
</asp:DataList>

I wanted to load my post title, description and publish the date in this Web Form. So I set the XPath property of my XMLDataSource to "rss/channel/item" (Look at the structure of my RSS) and used XPath between the ItemTemplate tags of the DataList control.

Here you can see the final result:

The last point about ItemTemplate tags is that you can change the formatting of your data easily as I have done with HTML tags. For example, here I change my title formatting to Bold/Italic:

<asp:XmlDataSource ID="XmlDataSource" DataFile="http://nayyeri.net/rss.aspx" 
XPath="rss/channel/item" runat="server"></asp:XmlDataSource>
<asp:DataList ID="DataList" runat="server" DataSourceID="XmlDataSource">
 <ItemTemplate>
     <font face="tahoma" size="6"><Strong><I><%#XPath("title")%></I><br />
     </Strong></font>
     <%#XPath("description")%><br />
     <font color="navy"><i><%#XPath("pubDate")%><br /></i></font>
 </ItemTemplate>
</asp:DataList>

Additional information

These are common applications of XMLDataSource. You can also use this control to save your data into XML files. To do this you need to use the Save method of XMLDataSource control. It will save all the memory cached data into your XML file (as you set in the DataFile property).

The XMLDataSource control doesn't support sorting and paging but you can do them with In-Memory data structures. Surely this won't be useful because you can use other data controls for this purpose.

Smart tag

Smart tags are very useful in ASP.NET 2. So, I'll try to describe the XMLDataSource control Smart Tag here. First look at this Smart tag snapshot:

Using the first choice (Configure Data Source) you can configure important properties of your XMLDataSource. If you open it you can choose Data File, Transform file (that's the XSL file and describes the structure of your Data file) and XPath expression.

The second choice is simple. It's just for refreshing control schema.

Bugs

There is an important bug in this control and you can read the full story here. Probably Microsoft will fix it in the RTM version.

History

  • 2005/07/05

    I wrote this article for ASP.NET 2.0 Beta 2. I'll update it for RTM version.

  • 2005/07/07

    On the basis of a comment, I have added the "Bug" topic. I have also added the "Smart Tag" topic in this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Keyvan Nayyeri
Web Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
For more information about me just visit my blog @ Nayyeri.NET

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionMy Vote Of 5memberAlireza_13622 Feb '13 - 21:16 
Thanks a lot
GeneralSiteMapDataSource Control in ASP.NetgroupAnkitaaguggi13 Oct '11 - 23:08 
This is great article, It's really helpful for me as well as this link
http://mindstick.com/Articles/63f98132-d931-41bd-bb16-37c0967a25e8/?XmlDataSource%20Control%20in%20ASP.Net[^]
also helped me to complete my task.
 
Laugh | :laugh: Thanks
GeneralMy vote of 4memberArt Schwalbenberg18 Aug '11 - 5:42 
A good article. I would like to thank Mr. Nayyeri for his work in posting it.
Generaldatelistmembervishalpanchal26 Jul '10 - 20:47 
How to Edit,Update and Delete in the Datalist
GeneralIs possible to put if logic on &lt;%#XPath("description") %&gt;memberAbhay Mhatre12 Jun '09 - 11:12 
I want to check length of description, and if length exceeds 100 characters, just want to use substring(0, 100) method on it, is it possible? if yes please give me example Confused | :confused:
 
Thank you.
GeneralRe: Is possible to put if logic on &lt;%#XPath("description") %&gt;memberrobert_smith7614 Jul '09 - 7:20 
You can call a function. (Sorry, going to do this in VB)
 
    Public Function Shorten(ByVal InString As String) As String
        If InString.Length > 100 Then
            Return InString.Substring(0, 99)
        Else
            Return InString
        End If
    End Function
 
And then to call that
 
        <asp:Repeater ID="Repeater" runat="server" DataSourceID="XmlDataSource1">
        <ItemTemplate>
        <strong><%#Shorten(XPath("Email"))%></strong><br />
        <%#XPath("Password")%><br />
        <asp:checkbox ID="ck1" runat="server" Checked='<%# XPath("Admin") %>' /><br />
        </ItemTemplate>
        </asp:Repeater>

Questionlimiting the number of records/data itemsmemberErandav25 Jan '09 - 21:25 
I'm using an xmldatasource control and display the data in a dataList control using an .
 
How can I limit the records being displayed - the original XML file contains 30 rows and I want to display only 5-10 with or without paging - how can I do that? the datalist control doesn't have a paging feature and I don't use a sql dB...
 
Any Tip will be appreciated...
 
Thanks

QuestionHow to get XML from asp:XmlDataSourcememberfthavha2 Dec '08 - 19:26 
I have 2 gridviews gvSelected and gvAll and a asp:XmlDataSource xmldataAllUsers in the page. the Xmldatasource is binded xml as eg given below in codebehind (C#)

 
<userinfo>
   <user selected="true">
      <userid>100</userid>
      <username>abcd</username>
   </user>
   <user selected="false">
      <userid>102</userid>
      <username>wxyz</username>
   </user>
</userinfo>
 
The Xml is generated in code behind using the data retrieved from DataBase
 
I bind the gvSelected and gvAll as  
 
xmldataAllUsers.XPath = "/userinfo/user[@selected='true']";
gvSelected.DataSource = xmldataAllUsers ;
gvSelected.DataBind();
 
xmldataAllUsers .XPath = "/userinfo/user[@selected='false']";
gvAll.DataSource = xmldataAllUsers;
gvAll.DataBind();
 
ie I am binding all nodes which have attribute "selected" value as "true" to gvSelected and "false" to gvAll
 
the aspx page is like
 
          <asp:XmlDataSource runat="server" ID="xmldataAllUsers"/>
                        <asp:GridView ID="gvSelected" runat="server" AutoGenerateColumns="false" OnRowCommand="_RowCommand">
                              <Columns>
                                    <asp:TemplateField>
                                          <ItemTemplate>
                                                      <%#XPath("username")%>
                                                      <asp:Button ID="btnAdd" runat="server" Text="+" CommandName="select" CommandArgument='<%#XPath("userid")%>'/>
                                          </ItemTemplate>
                                    </asp:TemplateField>
                              </Columns>
                        </asp:GridView>
          <asp:GridView ID="gvAll" runat="server" AutoGenerateColumns="false" OnRowCommand="_RowCommand">
                              <Columns>
                                    <asp:TemplateField>
                                          <ItemTemplate>
                                                      <%#XPath("username")%>                                                     
                                                      <asp:Button ID="btnRemove" runat="server" Text="-" CommandName="unselect" CommandArgument='<%#XPath("userid")%>'/>
                                          </ItemTemplate>
                                    </asp:TemplateField>
                              </Columns>
                        </asp:GridView>
 
So far everything is working fine, I am able to bind, On row command I am getting the command argument. Everything is perfect till here. Now my need/requirment is on row command
 
I need to get xml from xmldataAllUsers and change the attribute "selected" value to command name "select"/"unselect" and the command argument "userid" to true or false.
 
But I am not able to get XML from   xmldataAllUsers . I tried   following 2 ways
 
XmlDocument xmlDocUser = xmldataAllUsers.GetXmlDocument();
 
string strUserXml = xmldataAllUsers.Data;
 
Both didnt give me the values.
 
Please consider this doubt
 
Regards
AnswerRe: How to get XML from asp:XmlDataSourcememberfthavha4 Dec '08 - 1:55 
Any body please
QuestionCan we bind the datafile to the xmldatasource dynamicallymembersatigv9 May '08 - 4:46 
Hi, In the example you shown i am displaying an rsslink which is stored in the local xml file. For that i want to give DataFile as the data read from first xmldatasource. How can we do this. I am getting erros. The code i tried is:
<asp:xmldatasource id="XmlDataSource" runat="server" datafile="~/news.xml" xpath="categories/cheading">


<asp:repeater id="Repeater" runat="server" datasourceid="XmlDataSource">

<![CDATA[<%# XPath("@h") %>]]>

<%# XPath("category/crsslink").ToString()%>




" runat="server" OnInit="xmlrssid_Init" XPath="rss/chanel" OnDataBinding="xmlrssid_DataBinding" OnLoad="xmlrssid_Load" OnPreRender="xmlrssid_PreRender" OnTransforming="xmlrssid_Transforming" >




<asp:repeater id="rssid" runat="server" datasourceid="xmlrssid">

<%# XPath("title") %>


 
second xmldatasource is giving an error.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 4 Jul 2005
Article Copyright 2005 by Keyvan Nayyeri
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid