ASP tutorial. NET implementation XML insert and delete node information code
The following implementation inserts node information into the appropriate location in the XML file
Let's say we want to change the original XML file structure by inserting the node as follows
<computers> <computer id= "11111111" description= "Made in" > <name>lenovo</name> <price>5000</price> <color ismixed= "yes" >black</color> </computer>
<computer id= "2222222" description= "Made in USA" > <name>ibm</name> <price>10000</pric e> <color ismixed= "yes" >black</color> </computer> </computers>
using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Xml;
Namespace Operatexml
{
Class Program
{
static void Main (string[] args)
{
Try
{
XML File Storage Path
String Myxmlfilepath = "E:mycomputers.xml";
Adding node information to an XML file
Addxmlinformation (Myxmlfilepath);
}
catch (Exception ex)
{
Console.WriteLine (Ex.tostring ());
}
}
private static void Addxmlinformation (String xmlfilepath)
{
Try
{
XmlDocument myxmldoc = new XmlDocument ();
Myxmldoc.load (Xmlfilepath);
Add a node information with attributes
foreach (XmlNode node in myxmldoc.firstchild.childnodes)
{
XmlElement newelement = myxmldoc.createelement ("color");
Newelement.innertext = "BLACK";
Newelement.setattribute ("ismixed", "yes");
Node.appendchild (newelement);
}
Save changes
Myxmldoc.save (Xmlfilepath);
}
catch (Exception ex)
{
Console.WriteLine (Ex.tostring ());
}
}
}
}
The following implementation deletes the specified XML file node information (that is, removing the node just added) as follows:
using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Xml;
Namespace Operatexml
{
Class Program
{
static void Main (string[] args)
{
Try
{
XML File Storage Path
String Myxmlfilepath = "E:mycomputers.xml";
Delete XML file node information
Deletexmlinformation (Myxmlfilepath);
}
catch (Exception ex)
{
Console.WriteLine (Ex.tostring ());
}
}
private static void Deletexmlinformation (String xmlfilepath)
{
Try
{
XmlDocument myxmldoc = new XmlDocument ();
Myxmldoc.load (Xmlfilepath);
foreach (XmlNode node in myxmldoc.firstchild.childnodes)
{
Record the last child node under the node (short name: Last child node)
XmlNode lastnode = node.lastchild;
Delete the left and right child nodes under the last child node
Lastnode.removeall ();
Delete Last child node
Node.removechild (Lastnode);
}
Save changes to the XML file
Myxmldoc.save (Xmlfilepath);
}
catch (Exception ex)
{
Console.WriteLine (Ex.tostring ());
}
}
}
}