Thursday 9 June 2011

XML - Delete All Elements in XML Document

The penultamite one today in my tips is how to delete all elements in a XML Document

in c# use:

string filename = "categories.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath(filename));
XmlNode root = xmlDoc.DocumentElement;
XmlNodeList nodes = xmlDoc.SelectNodes("//Category");
foreach (XmlNode node in nodes)
{
node.ParentNode.RemoveChild(node);
}
xmlDoc.Save(Server.MapPath(filename));

and in vb.net use:

Dim filename As String = "categories.xml"
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.Load(Server.MapPath(filename))

Dim root As XmlNode = xmlDoc.DocumentElement
Dim nodes As XmlNodeList = xmlDoc.SelectNodes("//Category")

For Each node As XmlNode In nodes
node.ParentNode.RemoveChild(node)
Next
xmlDoc.Save(Server.MapPath(filename))

No comments:

Post a Comment