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

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

index.aspx 文件

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>XML管理平台(管理员)</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <%--<asp:BoundField DataField="id" HeaderText="编号" HeaderStyle-Width="100px" />
                <asp:BoundField DataField="key" HeaderText="属性名" />
                <asp:BoundField DataField="value" HeaderText="属性值" />
                <asp:BoundField DataField="explain" HeaderText="说明" />--%>
                <asp:TemplateField HeaderText="编号" >
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="属性名" HeaderStyle-Width="200px">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtKey" runat="server" Text='<%# Bind("key") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("key") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="属性值" HeaderStyle-Width="200px">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtValue" runat="server" Text='<%# Bind("value") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("value") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="说明" HeaderStyle-Width="200px">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtExplain" runat="server" Text='<%# Bind("explain") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("explain") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:CommandField ShowEditButton="True" ShowDeleteButton="true" HeaderText="操作" />
            </Columns>
        </asp:GridView>
        <br />
        <br />
        <div>
            id:<asp:TextBox ID="txt_Id" runat="server"></asp:TextBox> 
            属性名:<asp:TextBox ID="txt_Key" runat="server"></asp:TextBox> 
            属性值<asp:TextBox ID="txt_Value" runat="server"></asp:TextBox> 
            说明:<asp:TextBox ID="txt_Explain" runat="server"></asp:TextBox> 
            <asp:Button ID="Btn_Add" runat="server" Text="添加" OnClick="Btn_Add_Click" />
        </div>
    </div>
    </form>
</body>
</html>

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();
        }
        /// <summary>
        /// 更新xml数据
        /// </summary>
        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("<script>alert('" + key+value+explain + "');</script>");
            //通过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文件路径
        /// <summary>
        /// 返回当前XML文件路径
        /// </summary>
        /// <returns></returns>
        public string XmlFilePath()
        {
            return Server.MapPath("test.xml");
        }
        #endregion

        #region 返回加载的XML源
        /// <summary>
        /// 返回加载的xml源
        /// </summary>
        /// <returns></returns>
        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元素
        /// <summary>
        /// 删除XML元素
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="e"></param>
        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" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>XML管理平台(用户版)</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">
            <Columns>
                <asp:TemplateField HeaderText="编号" >
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="属性名" HeaderStyle-Width="200px">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("key") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="属性值" HeaderStyle-Width="200px">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtValue" runat="server" Text='<%# Bind("value") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Bind("value") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>

                <asp:TemplateField HeaderText="说明" HeaderStyle-Width="200px">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtExplain" runat="server" Text='<%# Bind("explain") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("explain") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" HeaderText="操作" />
            </Columns>
        </asp:GridView>
        <asp:Button ID="Btn_Down" runat="server" Text="下载配置文件" OnClick="Btn_Down_Click" />
    </div>
    </form>
</body>
</html>

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();
        }
        /// <summary>
        /// 更新xml数据
        /// </summary>
        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("<script>alert('" + key+value+explain + "');</script>");
            //通过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 文件

<?xml version="1.0" encoding="utf-8"?>
<information>
  <property>
    <id>1</id>
    <key>神兽</key>
    <value>皮卡丘</value>
    <explain>来自宠物小精灵</explain>
  </property>
  <property>
    <id>2</id>
    <key>神兽</key>
    <value>炎帝</value>
    <explain>来自宠物小精灵</explain>
  </property>
  <property>
    <id>3</id>
    <key>神兽</key>
    <value>水君</value>
    <explain>来自宠物小精灵</explain>
  </property>
  <property>
    <id>4</id>
    <key>神兽</key>
    <value>洛基亚</value>
    <explain>来自宠物小精灵</explain>
  </property>
  <property>
    <id>5</id>
    <key>神兽</key>
    <value>金刚武神兽</value>
    <explain>来自数码宝贝</explain>
  </property>
  <property>
    <id>6</id>
    <key>李逍遥</key>
    <value>御剑术</value>
    <explain>来自仙剑一的法术</explain>
  </property>
  <property>
    <id>7</id>
    <key>李逍遥</key>
    <value>万剑诀</value>
    <explain>来自仙剑一的法术</explain>
  </property>
</information>


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。