根据定制的 XML 文件进行随机抽取节
生活随笔
收集整理的這篇文章主要介紹了
根据定制的 XML 文件进行随机抽取节
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
此類庫中的兩個類可以達成這一的一些效果:每次打開網頁展現不同的標語、問候語,根據語錄內容隨機出題,隨機顯示新聞等等。當然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>");總結
以上是生活随笔為你收集整理的根据定制的 XML 文件进行随机抽取节的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FGSM(Fast Gradient S
- 下一篇: 设计模式系列之单例模式(java)