How To Create A Random Fact Generator Using XML
23 Apr 2008This is a simple little random fact generator which will show a new fact every time the page loads. After the initial load it will store the XML in the cache until the file is changed again.
XML: (Facts.xml)
<?xml version="1.0" encoding="utf-8" ?>
<facts>
<fact>
The numbers '172' can be found on the back of the U.S. $5 dollar
bill in the bushes at the base of the Lincoln Memorial.
</fact>
<fact>
President Kennedy was the fastest random speaker in the world
with upwards of 350 words per minute.
</fact>
<fact>
In the average lifetime, a person will walk the equivalent of 5
times around the equator.
</fact>
.
.
.
</facts>
Code: (RandomFact.ascx.cs)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.ComponentModel;
using System.Drawing.Design;
public partial class _controls_RandomFact : System.Web.UI.UserControl
{
private string _xmlDataSource;
[UrlProperty()]
public string XMLDataSource
{
get { return _xmlDataSource; }
set { _xmlDataSource = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
litFact.Text = getRandomFact();
}
private string getRandomFact()
{
Random rndIndex = new Random();
XmlDocument xmlDocFacts = new XmlDocument();
string strFact = string.Empty;
try
{
if (Cache["xmlDocFacts"] != null)
{
xmlDocFacts = (XmlDocument)Cache["xmlDocFacts"];
}
else
{
xmlDocFacts.Load(Server.MapPath(XMLDataSource));
Cache.Insert("xmlDocFacts", xmlDocFacts, new CacheDependency(Server.MapPath(XMLDataSource)));
}
XmlNodeList xmlNodesMessage = xmlDocFacts.SelectNodes("//fact");
int rnd = rndIndex.Next(0, xmlNodesMessage.Count);
strFact = Server.HtmlEncode(xmlNodesMessage[rnd].InnerText);
}
catch (Exception ex)
{
strFact = string.Format("<b>Error:</b> {0}", ex.Message);
}
return strFact;
}
}
Usage: (Default.aspx)
<uc1:RandomFact ID="RandomFact1" runat="server" XMLDataSource="App_Data/Facts.xml" />