Random Quotes using ASP.NET and XML

Saturday, October 27, 2007

I recently created a random quotes generator to be put up on my website. The code could be used to produce any random text on your website, where the text is defined in a XML file.

The following is the XML file for use with the code:

<?xml version="1.0" encoding="utf-8" ?>
<quotes>
<quote id="1">
<text>sample quote</text>
<author>sample author</author>
</quote>
<quote id="2">
<text>another quote</text>
<author>another author</author>
</quote>
.
.
<quote id="15">
<text>yet another quote</text>
<author>quote author</author>
</quote>
</quotes>
Save this file as quotes.xml in your ASP.NET project. Now open the page where you would like to place these random quotes. Create 2 labels in the page design with ids 'labelquote' and 'labelquoteauthor':

<asp:Label ID="labelquote" runat="server"&rt;</asp:Label&rt;
<asp:Label ID="labelquoteauthor" runat="server"&rt;</asp:Label&rt;


Now, add the following code to the 'Page_Load' method of this page:
string strquote;
string strquoteauthor;
Random r = new Random();
int random = r.Next(1, 15);

XmlTextReader reader = new XmlTextReader(Server.MapPath("quotes.xml"));
while (reader.Read())
{
if (reader.Name == "quote" &&
reader.GetAttribute("id") == random.ToString())
{
while (reader.Name != "text")
reader.Read();
strquote = reader.ReadElementContentAsString();
while (reader.Name != "author")
reader.Read();
strquoteauthor = reader.ReadElementContentAsString();
}
}
labelquote.Text = strquote;
labelquoteauthor.Text = strquoteauthor;
In the above code, the while loop reads all the lines of the Xml file and the quote having the specific random id is displayed.

You can also, make a user control from this code which you can add to each page or the master page of your website.

1 comments:

Anonymous said...

Exactly the starting point I needed for my project- thank you!

Post a Comment