Load data from XML : XmlNode « XML « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="HolmesQuote" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
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;

public partial class HolmesQuote : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    MyQuote quotes = new MyQuote(Server.MapPath("./Data.xml"));
    Quotation quote = quotes.GetRandomQuote();
    Response.Write("<b>" + quote.Source + "</b> (<i>" + quote.Date + "</i>)");
    Response.Write("<blockquote>" + quote.QuotationText + "</blockquote>");
      

  }
}
public class Quotation
{
  private string qsource;
  private string date;
  private string quotation;
  
  public Quotation(XmlNode quoteNode)
  {
    if ( (quoteNode.SelectSingleNode("source")) != null)
      qsource = quoteNode.SelectSingleNode("source").InnerText;
    if ( (quoteNode.Attributes.GetNamedItem("date")) != null)
      date = quoteNode.Attributes.GetNamedItem("date").Value;
    quotation = quoteNode.FirstChild.InnerText;
  }

  public string Source
  {
    get 
    {
      return qsource;

    }
    set 
    {
      qsource = value;
    }
  }

  public string Date
  {
    get 
    {
      return date;
    }
    set 
    {
      date = value;
    }
  }

  public string QuotationText
  {
    get 
    {
      return quotation;
    }
    set 
    {
      quotation = value;
    }
  }
}
public class MyQuote
{
  private XmlDocument quoteDoc;
  private int quoteCount;

  public MyQuote(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] );
  }

}

File: Data.xml

<?xml version="1.0"?>
<quotations>
  <quotation date="1887">
    <pre>A</pre>
    <source>W</source>
  </quotation>
  <quotation date="1887">
    <pre>t</pre>
    <source>S</source>
  </quotation>
</quotations>








25.11.XmlNode
25.11.1.Display data in XML file recursively (VB.net)
25.11.2.Load data from XML
25.11.3.MoveToNextAttribute