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" ?>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':
<text>yet another quote</text>
<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;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.
Random r = new Random();
int random = r.Next(1, 15);
XmlTextReader reader = new XmlTextReader(Server.MapPath("quotes.xml"));
if (reader.Name == "quote" &&
reader.GetAttribute("id") == random.ToString())
while (reader.Name != "text")
strquote = reader.ReadElementContentAsString();
while (reader.Name != "author")
strquoteauthor = reader.ReadElementContentAsString();
labelquote.Text = strquote;
labelquoteauthor.Text = strquoteauthor;
You can also, make a user control from this code which you can add to each page or the master page of your website.