This section provides an example of how to delete nodes in an XML file in a program. The results of the instance run are shown in Figure 1.
Program Development Steps:
(1) Create a new Web site whose homepage defaults to Default.aspx.
(2) Add an XML control to the Default.aspx page to display the contents of the XML file, and then add a TextBox control and a button control to enter the XML section name to be deleted and the delete operation to be performed.
(3) The main code of the program is as follows.
When you click the Delete button, the program first determines whether the content in the TextBox1 text box is empty, if not empty, finds the corresponding node in the XML file according to the contents of the TextBox1 text box, and deletes the node by XmlElement the RemoveChild method of the class. , the "Please enter the node to delete" Message prompt box, and redirect the page to the page. The Click event code for the Delete button is as follows:
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('请输入要删除的节点');location='javascript:history.go(-1)';</script>");
}
The complete program code is as follows:
★★★★★default.aspx Page Design file complete program code ★★★★★
<%@ Page language= "C #" autoeventwireup= "true" codefile= "Default.aspx.cs" inherits= "_default"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
<title> Delete XML node </title>
<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;"
Delete XML node </td></tr>
<tr>
<td style= font-size:9pt; 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= "title:" ></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= "delete"/></TD>
</tr
</table>
</div>
</form>
</body>