Deleting elements from XML Documents

If you need to delete either a Node, Element or Attribute from your XML document, try the following code as it actually works!!!

XML Document Structure

<?xml version=1.0encoding=utf-8standalone=yes?>
<!–
XML Config file–>
<Tests
>
<
Test>
<
ID>47d272cd-877d-4d0f-ad4a-cfa31200d966</ID>
<
Object>Obj1</Object>
<
TestType>Fail Yes</TestType>
<
Command>fail yes</Command>
<
Time>202</Time>
<
Expiry>0</Expiry>
</
Test>
<
Test>
<
ID>71b211a7-99e4-4041-ada7-2925b6aff46f</ID>
<
Object>Obj2</Object>
<
TestType>Fail No</TestType>
<
Command>fail no</Command>
<
Time>243</Time>
<
Expiry>0</Expiry>
</
Test>
</
Tests>

To delete the element based on the GUID I Use:

///
/// Allows you to delete an element from the XML File
///
/// String GUID ID to remove from the config file
/// Name of the element to delete
public void RemoveElement(string elementName, string id)
{
System
.Xml.XmlDocument doc = new System.Xml.XmlDocument();

doc.Load(filename);

System.Xml.XmlNodeList list = doc.GetElementsByTagName(Test);

for (int i = 0; i < list.Count; i++)
{

int j = 0;
for (j = 0; j < list[i].ChildNodes.Count; j++)
{

if (list[i].ChildNodes[j].Name.ToUpper() == “ID”)
break;
}

if (j < list[i].ChildNodes.Count && list[i].ChildNodes[0].InnerText == id)
{
System
.Xml.XmlNode parent = list[i].ParentNode;
parent
.RemoveChild(list[i]);
}
}
doc
.Save(filename);
}

Another way that i’ve not got around to testing (but which I like) is to use a DataView to suck the XML in, parse using the filter property and then after deleting, re-export as XML:

DataSet ds = new DataSet();
ds
.ReadXml(“xmlAdd file as above”);
if (ds != null && ds.Tables.Contains(“stickies”))
{

DataView dv = new DataView(ds.Tables[“stickies”]);
dv
.RowFilter = “id=1”;
if (dv.Count >= 1)
{
dv[
0].Delete();
ds
.AcceptChanges();
ds
.WriteXml(“updated.xml”);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.