首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 刪除 XML 節點實作(二):後端程式碼與 XML 資料

     編輯:關於C語言

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 控制項即時更新畫面。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved