不廢話,直接上如何利用Asp.NET操作XML文件,並對其屬性進行修改,剛開始的時候,是打算使用JS來控制生成XML文件的,但是最後卻是無法創建文件,讀取文件則沒有使用了 index.aspx 文件 index.aspx.cs文件 Command.cs 文件 UserEdit.aspx UserEd ...
不廢話,直接上如何利用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>