Asp.Net 操作XML文件的增删改查 利用GridView

不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了

index.aspx 文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="XmlManager.index" %>






    XML管理平台(管理员)


    
<%-- --%>

id:  属性名:  属性值  说明: 

index.aspx.cs文件

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace XmlManager
{
    public partial class index : System.Web.UI.Page
    {
        Command com = new Command();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGridView();
            }
        }

        //绑定数据
        private void LoadGridView()
        {
            this.GridView1.DataSource = Command.LoadDs().Tables[0];
            this.GridView1.DataBind();
        }
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            LoadGridView();
        }
        //数据更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Update(e);
            GridView1.EditIndex = -1;
            LoadGridView();
        }
        //取消编辑
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            LoadGridView();
        }
        /// 
        /// 更新xml数据
        /// 
        private void Update(GridViewUpdateEventArgs e)
        {
            string id=((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;
            string key = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtKey")).Text;
            string value = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtValue")).Text;
            string explain = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtExplain")).Text;
            //Response.Write("");
            //通过ID获取信息,然后更改信息
            XmlDocument doc = new XmlDocument();
            doc.Load(com.XmlFilePath());
            XmlNode information = doc.SelectSingleNode("information");//查找出根节点
            foreach (XmlNode property in information.ChildNodes)
            {
                XmlNode temp_node = property.FirstChild;
                if (temp_node.InnerText == id)
                {
                    //第一种方式
                    //property.RemoveAll();
                    //XmlElement ele_id = doc.CreateElement("id");
                    //ele_id.InnerText = id;
                    //property.AppendChild(ele_id);
                    //另外三个属性如上

                    //第二种方式
                    property.ChildNodes[1].InnerText = key;
                    property.ChildNodes[2].InnerText = value;
                    property.ChildNodes[3].InnerText = explain;
                    doc.Save(com.XmlFilePath());
                    break;
                }
            }
        }
        //删除
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Command.Delete(this.GridView1, e);
            LoadGridView();
        }
        //添加节点事件
        protected void Btn_Add_Click(object sender, EventArgs e)
        {
            Add();
            LoadGridView();
            this.txt_Id.Text = "";
            this.txt_Key.Text = "";
            this.txt_Value.Text = "";
            this.txt_Explain.Text = "";
        }
        //添加
        private void Add()
        {
            string id = this.txt_Id.Text;
            string key = this.txt_Key.Text;
            string value = this.txt_Value.Text;
            string explain = this.txt_Explain.Text;
            //从最后一个插入一条数据
            XmlDocument doc = new XmlDocument();
            doc.Load(com.XmlFilePath());
            XmlNode information = doc.SelectSingleNode("information");
            XmlElement property = doc.CreateElement("property");
            
            XmlElement ele_id = doc.CreateElement("id");
            ele_id.InnerText = id;
            property.AppendChild(ele_id);

            XmlElement ele_key = doc.CreateElement("key");
            ele_key.InnerText = key;
            property.AppendChild(ele_key);

            XmlElement ele_value = doc.CreateElement("value");
            ele_value.InnerText = value;
            property.AppendChild(ele_value);

            XmlElement ele_explain = doc.CreateElement("explain");
            ele_explain.InnerText = explain;
            property.AppendChild(ele_explain);

            information.InsertAfter(property, information.LastChild);
            doc.Save(com.XmlFilePath());
        }
    }
}

Command.cs 文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace XmlManager
{
    public class Command:System.Web.UI.Page
    {
        #region 返回当前XML文件路径
        /// 
        /// 返回当前XML文件路径
        /// 
        /// 
        public string XmlFilePath()
        {
            return Server.MapPath("test.xml");
        }
        #endregion

        #region 返回加载的XML源
        /// 
        /// 返回加载的xml源
        /// 
        /// 
        public static DataSet LoadDs()
        {
            Command com = new Command();
            //转换一个XML文件(本地\网络均可)为一个DataSet
            DataSet ds = new DataSet();
            StringReader sreader = null;
            XmlTextReader xtreader = null;
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(com.XmlFilePath());
                sreader = new StringReader(doc.InnerXml);
                xtreader = new XmlTextReader(sreader);
                ds.ReadXml(xtreader);
            }
            catch
            {
                throw;
            }
            finally
            {
                xtreader.Close();
                sreader.Close();
            }
            return ds;
        }
        #endregion

        #region 删除XML元素
        /// 
        /// 删除XML元素
        /// 
        /// 
        /// 
        public static void Delete(GridView grid, GridViewDeleteEventArgs e)
        {
            Command com = new Command();
            XmlDocument doc = new XmlDocument();
            doc.Load(com.XmlFilePath());
            XmlNode information = doc.SelectSingleNode("information");
            foreach (XmlNode property in information.ChildNodes)
            {
                XmlNode node_id = property.FirstChild;
                if (node_id.InnerText == ((Label)grid.Rows[e.RowIndex].FindControl("Label1")).Text)
                {
                    property.ParentNode.RemoveChild(property);
                }
            }
            doc.Save(com.XmlFilePath());
        }
        #endregion
       
    }
}

UserEdit.aspx 文件

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserEdit.aspx.cs" Inherits="XmlManager.UserEdit" %>






    XML管理平台(用户版)


    

UserEdit.aspx.cs 文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace XmlManager
{
    public partial class UserEdit : System.Web.UI.Page
    {
        Command com = new Command();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGridView();
            }
        }
        //绑定数据
        private void LoadGridView()
        {
            this.GridView1.DataSource = Command.LoadDs().Tables[0];
            this.GridView1.DataBind();
        }
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            LoadGridView();
        }
        //数据更新
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Update(e);
            GridView1.EditIndex = -1;
            LoadGridView();
        }
        //取消编辑
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            LoadGridView();
        }
        /// 
        /// 更新xml数据
        /// 
        private void Update(GridViewUpdateEventArgs e)
        {
            string id = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;
            string key = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label2")).Text;
            string value = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtValue")).Text;
            string explain = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtExplain")).Text;
            //Response.Write("");
            //通过ID获取信息,然后更改信息
            XmlDocument doc = new XmlDocument();
            doc.Load(com.XmlFilePath());
            XmlNode information = doc.SelectSingleNode("information");//查找出根节点
            foreach (XmlNode property in information.ChildNodes)
            {
                XmlNode temp_node = property.FirstChild;
                if (temp_node.InnerText == id)
                {
                    //第一种方式
                    //property.RemoveAll();
                    //XmlElement ele_id = doc.CreateElement("id");
                    //ele_id.InnerText = id;
                    //property.AppendChild(ele_id);
                    //另外三个属性如上

                    //第二种方式
                    property.ChildNodes[1].InnerText = key;
                    property.ChildNodes[2].InnerText = value;
                    property.ChildNodes[3].InnerText = explain;
                    doc.Save(com.XmlFilePath());
                    break;
                }
            }
        }
        //流方式下载
        protected void Btn_Down_Click(object sender, EventArgs e)
        {
            string fileName = "user.xml";//客户端保存的文件名
            string filePath = com.XmlFilePath();//下载的路径
            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";//设置输出流类型——二进制
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}

test.xml 文件



  
    1
    神兽
    皮卡丘
    来自宠物小精灵
  
  
    2
    神兽
    炎帝
    来自宠物小精灵
  
  
    3
    神兽
    水君
    来自宠物小精灵
  
  
    4
    神兽
    洛基亚
    来自宠物小精灵
  
  
    5
    神兽
    金刚武神兽
    来自数码宝贝
  
  
    6
    李逍遥
    御剑术
    来自仙剑一的法术
  
  
    7
    李逍遥
    万剑诀
    来自仙剑一的法术
  


你可能感兴趣的:(C#)