关闭

ASP.NET对XML进行读,改,删操作代码

311人阅读 评论(0) 收藏 举报

user.xml内容如下:

<?xml version="1.0" encoding="GB2312"?>
<UserInfo>
  <datarow>
    <username>adsfasdfasdfaaaaaa</username>
    <password>23451111111</password>
    <study>高中</study>
  </datarow>
  <datarow>
    <username>adsfasdfasdf</username>
    <password>23451111111</password>
    <study>高中</study>
  </datarow>
  <datarow>
    <username>lingyubin222222</username>
    <password>520520</password>
    <study>大学</study>
  </datarow>
  <datarow>
    <username>lingyubin1232</username>
    <password>520520</password>
    <study>大学</study>
  </datarow>
  <datarow>
    <username>lingyubin123232</username>
    <password>520520</password>
    <study>大学</study>
  </datarow>
  <datarow>
    <username>23213</username>
    <password>3232332</password>
    <study>高中</study>
  </datarow>
  <datarow>
    <username>3423123</username>
    <password>3213</password>
    <study>小学</study>
  </datarow>
</UserInfo>

WebForm.aspx内容:

 

<%@ Page language="c#" Codebehind="WebForm2.aspx.cs" AutoEventWireup="false" Inherits="StudyTest.新博机试题.WebForm2" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
  <HEAD>
  <title>WebForm2</title>
  <meta content="Microsoft Visual Studio .NET 7.1" 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">
  </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <table cellSpacing="0" cellPadding="0" align="center" border="0">
    <tr>
     <td>用户名:
      <asp:textbox id="TextBox1" runat="server"></asp:textbox></td>
     <td>密码:<asp:textbox id="Textbox2" runat="server"></asp:textbox>
     </td>
     <td>学历:
      <asp:dropdownlist id="DropDownList1" runat="server">
       <asp:ListItem Value="大学">大学</asp:ListItem>
       <asp:ListItem Value="高中">高中</asp:ListItem>
       <asp:ListItem Value="小学">小学</asp:ListItem>
      </asp:dropdownlist></td>
     <td><asp:button id="btn_Add" runat="server" Text="增 加"></asp:button></td>
    </tr>
   </table>
   <br>
   <br>
   <table cellSpacing="0" cellPadding="0" align="center" border="0">
    <tr>
     <td><asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" BorderColor="#CCCCCC"
       BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="3">
       <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
       <ItemStyle ForeColor="#000066"></ItemStyle>
       <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699"></HeaderStyle>
       <FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
       <Columns>
        <asp:TemplateColumn>
         <HeaderTemplate>
          用户名
         </HeaderTemplate>
         <ItemTemplate>
          <asp:Label id="Label1" runat="server">
           <%#DataBinder.Eval(Container,"DataItem.username")%>
          </asp:Label>
         </ItemTemplate>
         <EditItemTemplate>
          <asp:TextBox Runat=server ID="Textbox3" Text='<%#DataBinder.Eval(Container,"DataItem.username")%>'>
          </asp:TextBox>
         </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
         <HeaderTemplate>
          密码
         </HeaderTemplate>
         <ItemTemplate>
          <asp:Label id="Label2" runat="server">
           <%#DataBinder.Eval(Container,"DataItem.password")%>
          </asp:Label>
         </ItemTemplate>
         <EditItemTemplate>
          <asp:TextBox id="Textbox4" runat="server" Text='<%#DataBinder.Eval(Container,"DataItem.password")%>'>
          </asp:TextBox>
         </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:TemplateColumn>
         <HeaderTemplate>
          学历
         </HeaderTemplate>
         <ItemTemplate>
          <asp:Label id="Label3" runat="server">
           <%#DataBinder.Eval(Container,"DataItem.study")%>
          </asp:Label>
         </ItemTemplate>
         <EditItemTemplate>
          <asp:DropDownList id="Dropdownlist2" runat="server">
           <asp:ListItem Value="大学">大学</asp:ListItem>
           <asp:ListItem Value="高中">高中</asp:ListItem>
           <asp:ListItem Value="小学">小学</asp:ListItem>
          </asp:DropDownList>
         </EditItemTemplate>
        </asp:TemplateColumn>
        <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
        <asp:ButtonColumn Text="删除" CommandName="Delete"></asp:ButtonColumn>
       </Columns>
      </asp:datagrid></td>
    </tr>
   </table>
  </form>
 </body>
</HTML>


WebForm.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;
using System.IO;

 

namespace StudyTest.新博机试题
{
 /// <summary>
 /// WebForm2 的摘要说明。
 /// </summary>
 public class WebForm2 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.WebControls.TextBox Textbox2;
  protected System.Web.UI.WebControls.DropDownList DropDownList1;
  protected System.Web.UI.WebControls.Button btn_Add;
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!IsPostBack)
   {
    ReadXML();
   }
  }

  #region 显示XML数据
  private void ReadXML()
  {
   string url = Server.MapPath("user.xml");//获得当前文件夹下的XML文件
   StreamReader sRead = new StreamReader(url,System.Text.Encoding.GetEncoding("GB2312"));//以一种特定的编码从字节流读取字符,必须要转化成GB2312读取才不能出乱码
   XmlDataDocument datadoc = new XmlDataDocument();//操作XML文档
   datadoc.DataSet.ReadXml(sRead);//将读取的字节流存到DataSet里面去
   this.DataGrid1.DataSource = datadoc.DataSet.Tables[0].DefaultView;
   DataGrid1.DataKeyField="username";//以username建立索引
   this.DataGrid1.DataBind();
   datadoc = null;//清空对XML数据的操作
   sRead.Close();//关闭字节流的读取
  }
  #endregion


  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.btn_Add.Click += new System.EventHandler(this.btn_Add_Click);
   this.DataGrid1.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_CancelCommand);
   this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_EditCommand);
   this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand);
   this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_DeleteCommand);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  #region 往XML插入数据
  private void btn_Add_Click(object sender, System.EventArgs e)
  {
   string url = Server.MapPath("user.xml");
   string str_username = this.TextBox1.Text.ToString();
   string str_password = this.Textbox2.Text.ToString();
   string str_study = this.DropDownList1.SelectedValue.ToString();
   try
   {
    XmlDocument xmlDoc=new XmlDocument();
    xmlDoc.Load(url); //加载XML文档
    XmlNode root=xmlDoc.SelectSingleNode("UserInfo");//查找第一个匹配的XmlNode
    XmlElement xe1=xmlDoc.CreateElement("datarow");//创建第一个节点的第一个元素

    XmlElement xesub1=xmlDoc.CreateElement("username"); //创建第一个节点的第一个元素里的属性
    xesub1.InnerText=str_username;//设置文本节点
    xe1.AppendChild(xesub1);//将指定节点添加到该节点的子节点列表的末尾
    XmlElement xesub2=xmlDoc.CreateElement("password");
    xesub2.InnerText=str_password;
    xe1.AppendChild(xesub2);
    XmlElement xesub3=xmlDoc.CreateElement("study");
    xesub3.InnerText=str_study;
    xe1.AppendChild(xesub3);

    root.AppendChild(xe1);
    xmlDoc.Save (url);//保存XML文件

    ReadXML();
   }
   catch (Exception ex)
   {
    Response.Write(ex.ToString());
   }

  }
  #endregion

  #region 编辑取消

  private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex = e.Item.ItemIndex;
   ReadXML();
  }

  private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   this.DataGrid1.EditItemIndex = -1;
   ReadXML();
  }
  #endregion

  #region 修改XML数据

  private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string url = Server.MapPath("user.xml");

   string str_username=DataGrid1.DataKeys[e.Item.ItemIndex].ToString();


   TextBox txt_username = (TextBox)e.Item.FindControl("Textbox3");
   TextBox txt_password = (TextBox)e.Item.FindControl("Textbox4");
   DropDownList drp_study=(DropDownList)e.Item.FindControl("DropDownList2");

   XmlDocument xmlDoc=new XmlDocument();
   xmlDoc.Load(url); //加载XML文件
   XmlNode root=xmlDoc.SelectSingleNode("UserInfo");//查找UserInfo节点
   XmlNodeList xnl=root.ChildNodes; //获取UserInfo下面所以子节点
   for(int i=0;i<xnl.Count;i++)
   {
    XmlNodeList xnl11=xnl.Item(i).SelectNodes("username");//查找username下面节点集合
    XmlElement xe=(XmlElement)xnl11.Item(0); //username节点下面的元素
    if(xe.InnerText==str_username) //获取节点以及所有子集的串联值
    {
     xe.InnerText=txt_username.Text;
     xe.ParentNode.ChildNodes.Item(1).InnerText=txt_password.Text;
     xe.ParentNode.ChildNodes.Item(2).InnerText=drp_study.SelectedValue;
    }

   }
   xmlDoc.Save(url);
   this.DataGrid1.EditItemIndex = -1;
   ReadXML();
   
  }
  #endregion

  #region 删除XML数据

  private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
  {
   string url = Server.MapPath("user.xml");

   string str_username=DataGrid1.DataKeys[e.Item.ItemIndex].ToString();

   XmlDocument xmlDoc=new XmlDocument();
   xmlDoc.Load(url); //加载XML文件
   XmlNode root=xmlDoc.SelectSingleNode("UserInfo");//查找UserInfo节点
   XmlNodeList xnl=root.ChildNodes; //获取UserInfo下面所以子节点
   for(int i=0;i<xnl.Count;i++)
   {
    XmlNodeList xnl11=xnl.Item(i).SelectNodes("username");//查找username下面节点集合
    XmlElement xe=(XmlElement)xnl11.Item(0); //username节点下面的元素
    if(xe.InnerText==str_username) //获取节点以及所有子集的串联值
    {
     
     root.RemoveChild(xe.ParentNode);//移除指顶节点
//     xe.ParentNode.RemoveChild(xe);
//     xnl.Item(i).RemoveChild(xe);
//     if(i<xnl.Count)i=i-1;
    }
   }
   xmlDoc.Save(url);
   ReadXML();
  }
  #endregion

 }

}

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:248157次
    • 积分:3399
    • 等级:
    • 排名:第10225名
    • 原创:21篇
    • 转载:306篇
    • 译文:3篇
    • 评论:42条