用一个留言簿说明C#操作XML的完全过程

类别:.NET开发 点击:0 评论:0 推荐:

第一步:在项目文件里创建db文件夹,在db文件夹里创建db.xml文档。db.xml结构只包含:<Group></Group>

第二步:新建添加留言和显示留言的两个画面:MessageAdd.aspx和MessageList.aspx。下面是两个页面的  前台和后台源码。

//--------------------Begin--------------------//

1.MessageAdd.aspx

 
<%@ Page language="c#" Codebehind="MessageAdd.aspx.cs" AutoEventWireup="false" Inherits="XMLGuest.MessageAdd" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>MessageAdd</title>
  <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  <style>.Txt1 {
 FONT-SIZE: 12px
}
  </style>
 </HEAD>
 <body>
  <form id="MessageAdd" method="post" runat="server">
   <FONT face="宋体">
    <P>&nbsp;</P>
    <P align="center">
     <TABLE class="Txt1" id="Table1" cellSpacing="1" cellPadding="4" width="749" bgColor="#efefef"
      border="0">
      <TR>
       <TD bgColor="#e8dabd">您的大名</TD>
       <TD style="WIDTH: 508px" bgColor="#ffffff"><asp:textbox id="TextBoxUName" runat="server" LeaveSQL="False" LeaveFormat="False" HtmlEncode="False"
         Width="519px" MaxLength="10" CssClass="TextAreaClass"></asp:textbox></TD>
       <TD bgColor="#ffffff" colSpan="1" rowSpan="1"></TD>
      </TR>
      <TR>
       <TD bgColor="#e8dabd" colSpan="1" rowSpan="1">E-Mail</TD>
       <TD style="WIDTH: 505px" bgColor="#ffffff">
        <P><asp:textbox id="TextBoxMail" runat="server" LeaveSQL="False" LeaveFormat="False" HtmlEncode="False"
          Width="519px" MaxLength="30" CssClass="TextAreaClass"></asp:textbox></P>
       </TD>
       <TD bgColor="#ffffff" colSpan="1" rowSpan="1"><BR>
       </TD>
      </TR>
      <TR>
       <TD bgColor="#e8dabd" colSpan="1" rowSpan="1">内容</TD>
       <TD style="WIDTH: 505px" bgColor="#ffffff">
        <P><asp:textbox id="TextBoxTxt" runat="server" LeaveSQL="False" LeaveFormat="True" HtmlEncode="False"
          Width="519px" TextMode="MultiLine" Height="160px"></asp:textbox></P>
       </TD>
       <TD bgColor="#ffffff" colSpan="1" rowSpan="1"></TD>
      </TR>
     </TABLE>
    </P>
    <P align="center"><asp:button id="Button1" runat="server" CssClass="TextAreaClass" Text=" 提交 "></asp:button>&nbsp;&nbsp;&nbsp;&nbsp;
     &nbsp; <INPUT class="TextAreaClass" onclick="window.location.replace('MessageList.aspx')" type="button"
      value=" 返回 "></P>
   </FONT>
  </form>
 </body>
</HTML>

MessageAdd.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace XMLGuest
{
 /// <summary>
 /// MessageAdd 的摘要说明。
 /// </summary>
 public class MessageAdd : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.TextBox TextBoxUName;
  protected System.Web.UI.WebControls.TextBox TextBoxMail;
  protected System.Web.UI.WebControls.TextBox TextBoxTxt;
  protected System.Web.UI.WebControls.Button Button1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   
    XmlDocument doc = new XmlDocument();
    doc.Load(MapPath("db\\db.xml"));
    XmlNode node = doc.CreateElement("Item");
     
    XmlAttribute xmlattr = doc.CreateAttribute("UserName");
    xmlattr.Value = XmlConvert.DecodeName(TextBoxUName.Text);
    node.Attributes.Append(xmlattr);

    xmlattr = doc.CreateAttribute("UserEmail");
    xmlattr.Value = XmlConvert.DecodeName(TextBoxMail.Text);
    node.Attributes.Append(xmlattr);

    xmlattr = doc.CreateAttribute("Content");
    xmlattr.Value = XmlConvert.DecodeName(TextBoxTxt.Text);
    node.Attributes.Append(xmlattr);

    xmlattr = doc.CreateAttribute("SendTime");
    xmlattr.Value = XmlConvert.DecodeName(DateTime.Now.ToString());
    node.Attributes.Append(xmlattr);

    doc.ChildNodes[0].AppendChild(node);
    doc.Save(MapPath("db\\db.xml"));
    Response.Redirect("MessageList.aspx");
    
  }
 }
}

2.MessageList.aspx

<%@ Page language="c#" Codebehind="MessageList.aspx.cs" AutoEventWireup="false" Inherits="XMLGuest.MessageList" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>MessageList</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  <style>
  .body { FONT-SIZE: 12px }
  .td1 { FONT-SIZE: 12px }
  </style>
 </HEAD>
 <body class="body">
  <form id="MessageList" method="post" runat="server">
   <P align="right">
    <asp:HyperLink id="GrowHyperLink1" runat="server" Text="[留言]" NavigateUrl="MessageAdd.aspx"></asp:HyperLink>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   </P>
   <P align="center"><FONT face="宋体"></FONT><FONT face="宋体"></FONT><BR>
    <asp:DataGrid id="DataList1" runat="server" AutoGenerateColumns="False" ShowHeader="False" PageSize="15"
     BorderStyle="None" BorderWidth="0px" CellPadding="4" Font-Size="12px">
     <Columns>
      <asp:TemplateColumn>
       <ItemTemplate>
        <TABLE id="Table7" borderColor="#efefef" cellSpacing="0" cellPadding="4" width="749" bgColor="#efefef"
         border="1">
         <TR class="td1" bgColor="#fafafa">
          <TD style="WIDTH: 200px" bgColor="#ffffff"><STRONG>姓名:</STRONG>
           <asp:Label id=Label5 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.UserName").ToString() %>'>
           </asp:Label>&nbsp;&nbsp;
          </TD>
          <TD style="WIDTH: 150px" bgColor="#ffffff"><STRONG><FONT face="宋体">时间</FONT></STRONG><STRONG><FONT face="宋体">:</FONT></STRONG>
           <asp:Label id=Label4 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.SendTime").ToString() %>'>
           </asp:Label></TD>
          <TD bgColor="#ffffff"><STRONG>E-Mail</STRONG><STRONG>:
            <asp:HyperLink id=HyperLink1 runat="server" NavigateUrl='<%# "mailto:"+DataBinder.Eval(Container, "DataItem.UserEmail").ToString() %>' Text='<%# DataBinder.Eval(Container, "DataItem.UserEmail").ToString() %>'>
            </asp:HyperLink></STRONG></TD>
         </TR>
         <TR class="td1">
          <TD bgColor="#ffffff" colSpan="3">
           <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Content").ToString() %>'>
           </asp:Label></TD>
         </TR>
        </TABLE>
       </ItemTemplate>
      </asp:TemplateColumn>
     </Columns>
     <PagerStyle Visible="False"></PagerStyle>
    </asp:DataGrid>
   </P>
  </form>
 </body>
</HTML>

MessageList.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;

namespace XMLGuest
{
 /// <summary>
 /// MessageList 的摘要说明。
 /// </summary>
 public class MessageList : System.Web.UI.Page
 {
  protected HyperLink GrowHyperLink1;
  protected System.Web.UI.WebControls.DataGrid DataList1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   FileStream stream = new FileStream(Server.MapPath("db\\db.xml"),FileMode.Open);
   try
   {
    XmlDataDocument doc = new XmlDataDocument();
    doc.DataSet.ReadXml(new StreamReader(stream));
    if(doc.DataSet.Tables.Count != 0 && doc.DataSet.Tables[0].Rows.Count!=0)
    {
     DataList1.DataSource = doc.DataSet.Tables[0].DefaultView ;
     DataList1.DataBind();
    }
    stream.Close();
   }
   catch(Exception ding)
   {
    Response.Write(ding.Message);
   }
   finally
   {
    stream.Close();
   }
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }
}

//---------------------End----------------------//


本文地址:http://com.8s8s.com/it/it41175.htm