Default.aspx.cs 完整程式碼
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("test.xml"));
XslTransform trans = new XslTransform();
trans.Load(Server.MapPath("test.xsl"));
XML1.Document = doc;
XML1.Transform = trans;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text.Trim() != "")
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("test.xml"));
XmlNodeList nodes;
XmlElement root = doc.DocumentElement;
nodes = root.SelectNodes("descendant::BOOK[TITLE='" + TextBox1.Text.Trim() + "']");
foreach (XmlNode node in nodes)
{
root.RemoveChild(node);
}
TextBox1.Text = "";
Response.Write("<script>alert('刪除成功')</script>");
doc.Save(Server.MapPath("test.xml"));
XslTransform trans = new XslTransform();
trans.Load(Server.MapPath("test.xsl"));
XML1.Document = doc;
XML1.Transform = trans;
}
else
{
Response.Write("<script>alert('請輸入要刪除的節點')</script>");
}
}
}
test.xml 範例資料
<?xml version="1.0" encoding="utf-8"?>
<PUBLICATION>
<BOOK>
<TITLE>C#資料庫系統開發完全手冊</TITLE>
<PAGES>628</PAGES>
</BOOK>
</PUBLICATION>
關鍵點說明
- 使用
SelectNodes 搭配 XPath descendant::BOOK[TITLE='...'] 精準定位節點。
- 刪除後需呼叫
doc.Save 持久化變更。
- 重新載入 XSLT 並繫結至
Xml 控制項即時更新畫面。