XML 是常見的資料交換與儲存格式。本文示範在 ASP.NET Web Forms 中使用 XmlDocument 載入、查詢、刪除 XML 節點,並搭配 XSLT 轉換顯示於 asp:Xml 控制項的完整流程。
Default.aspx:前端頁面,包含輸入框、刪除按鈕、XML 顯示區Default.aspx.cs:後端邏輯,處理刪除與資料繫結test.xml:資料來源 XML 檔案test.xsl:XSLT 樣式表,將 XML 轉換為 HTML 表格顯示<?xml version="1.0" encoding="utf-8"?>
<PUBLICATION>
<BOOK>
<TITLE>C#資料庫系統開發完全手冊</TITLE>
<PAGES>628</PAGES>
</BOOK>
</PUBLICATION>
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="https://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table width="300" border="10" cellspacing="0" cellpadding="0" style="font-size: 9pt;">
<tr align="center">
<td style="font-size: 9pt;">書名</td>
<td style="font-size: 9pt;">頁碼</td>
</tr>
<xsl:for-each select="PUBLICATION/BOOK">
<tr align="center" height="30">
<td><xsl:value-of select="TITLE"/></td>
<td><xsl:value-of select="PAGES"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>刪除XML節點</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="1" cellpadding="0" cellspacing="0" style="width: 245px" bordercolor="#66cccc">
<tr>
<td style="font-size: 9pt; background-color: #66cccc; text-align: center;">刪除XML節點</td>
</tr>
<tr>
<td style="font-size: 9pt; text-align: center; background-color: #ccffff;">
<asp:Xml ID="Xml1" runat="server"></asp:Xml>
</td>
</tr>
<tr>
<td style="text-align: center; font-size: 9pt; background-color: #ccffff;">
<asp:Label ID="Label1" runat="server" Font-Size="9pt" Text="書名:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Font-Size="9pt" Width="92px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Font-Size="9pt" OnClick="Button1_Click" Text="刪除" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using System;
using System.Xml;
using System.Xml.Xsl;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindXmlData();
}
private void BindXmlData()
{
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)
{
string title = TextBox1.Text.Trim();
if (string.IsNullOrEmpty(title))
{
ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('請輸入要刪除的節點');", true);
return;
}
try
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("test.xml"));
XmlElement root = doc.DocumentElement;
// XPath 查詢:尋找 TITLE 符合輸入值的 BOOK 節點
XmlNodeList nodes = root.SelectNodes($"descendant::BOOK[TITLE='{title}']");
if (nodes.Count == 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert",
$"alert('找不到書名為「{title}」的節點');", true);
return;
}
foreach (XmlNode node in nodes)
{
root.RemoveChild(node);
}
doc.Save(Server.MapPath("test.xml"));
TextBox1.Text = "";
ClientScript.RegisterStartupScript(this.GetType(), "alert",
"alert('刪除成功');", true);
BindXmlData(); // 重新繫結顯示
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "alert",
$"alert('刪除失敗:{ex.Message}');", true);
}
}
}
| 語法 | 說明 | 範例 |
|---|---|---|
//BOOK | 所有 BOOK 節點(任意深度) | 選取所有書本 |
/PUBLICATION/BOOK | 特定路徑的 BOOK 節點 | 僅第一層書本 |
BOOK[TITLE='C#'] | 條件篩選 | 書名為 C# 的節點 |
descendant::BOOK | 所有後代 BOOK 節點 | 跨層級查詢 |
Load(path):從檔案載入 XMLSelectNodes(xpath):查詢符合條件的節點集合SelectSingleNode(xpath):查詢單一節點RemoveChild(node):移除子節點Save(path):儲存變更至檔案XmlDocument 載入資料XslTransform 載入樣式表asp:Xml 控制項的 Document 與 Transform 屬性.NET 3.5+ 建議使用 System.Xml.Linq,語法更直觀:
using System.Xml.Linq;
XDocument doc = XDocument.Load(Server.MapPath("test.xml"));
// 查詢並刪除
var books = doc.Descendants("BOOK")
.Where(b => b.Element("TITLE")?.Value == title)
.ToList();
foreach (var book in books)
book.Remove();
doc.Save(Server.MapPath("test.xml"));
' or '1'='1 可能刪除所有節點XmlElement newBook = doc.CreateElement("BOOK");
XmlElement titleEl = doc.CreateElement("TITLE");
titleEl.InnerText = "新書名";
XmlElement pagesEl = doc.CreateElement("PAGES");
pagesEl.InnerText = "300";
newBook.AppendChild(titleEl);
newBook.AppendChild(pagesEl);
root.AppendChild(newBook);
XmlNode book = root.SelectSingleNode($"descendant::BOOK[TITLE='{oldTitle}']");
if (book != null)
{
book.SelectSingleNode("TITLE").InnerText = newTitle;
book.SelectSingleNode("PAGES").InnerText = newPages;
doc.Save(path);
}
XML 節點刪除涉及載入、XPath 查詢、移除、儲存四個核心步驟。搭配 XSLT 可直接在 Web 頁面呈現結構化資料。現代開發建議改用 LINQ to XML 獲得型別安全與更優雅的語法,並務必注意 XPath 注入風險與檔案權限管理。