此类库中的两个类可以达成这一的一些效果:每次打开网页展现不同的标语、问候语,根据语录内容随机出题,随机显示新闻等等。当然XML格式的定制或者根据不同的XML文件适当修改类字段还是必要的。
using System;
using System.Xml;
namespace Quotations
{
public class QuotationManager
{
private XmlDocument quoteDoc;
private int quoteCount;
public QuotationManager(string fileName)
{
quoteDoc = new XmlDocument();
quoteDoc.Load(fileName);
quoteCount = quoteDoc.DocumentElement.ChildNodes.Count;
}
public Quotation GetRandomQuote()
{
int i;
Random x = new Random();
i = x.Next(quoteCount - 1);
return new Quotation(quoteDoc.DocumentElement.ChildNodes[i]);
}
}
}
using System;
using System.Xml;
namespace Quotations
{
public class Quotation
{
public string Source { get; set; }
public string Date { get; set; }
public string QuotationText { get; set; }
public Quotation(XmlNode quoteNode)
{
if (quoteNode.SelectSingleNode("source") != null)
{
Source = quoteNode.SelectSingleNode("source").InnerText;
}
if (quoteNode.SelectSingleNode("date")!=null)
{
Date = quoteNode.SelectSingleNode("date").InnerText;
}
QuotationText = quoteNode.FirstChild.InnerText;
}
}
}
这样调用:
string filePath = Server.MapPath("./quotations.xml");
Quotations.QuotationManager manager = new Quotations.QuotationManager(filePath);
Quotations.Quotation quotation = manager.GetRandomQuote();
Response.Write("<b>" + quotation.Source + "</b>(<i>" + quotation.Date + "</i>)");
Response.Write("<blockquote>" + quotation.QuotationText + "</blockquote>");