Different ways of removing elements from XML

Linq to XML provides numerous ways of modifying XML which includes adding, updating and deleting nodes. I happen to work on an XML document from which I had to remove some xelments. Surprisingly I found numerous options that facilitate deleting of various xelements from  XML loaded in memory. Depending on where you are in the XML tree, you might find one method easier than the other. Here is a simple example that illustrates various ways I discovered of removing xelements from XML loaded in memory.

image

image

In the above example, I have some XML elements nested inside of book element. I start of with deleting title element by first getting access to the title element by using element method. Once I have the instance of the element that I want to remove I simply call remove on the element to remove the element from the tree.

Next, I am deleting ISBN number by calling SetElementValue. Basically SetElementValue takes an element and the value for the element. If the element does not exists, it gets added. If element is present in the tree, the value gets updated. However if the value is set to null, the element gets removed from the tree.

In the last option, I am removing the totalchapters element by first getting a reference to the element and calling the replaceWith method passing null for the element parameter. ReplaceWith method takes an element that you want the existing element to be replaced with. Passing value of null indicates that you want to simply remove the existing element.

From the output, you can confirm that title, ISBN and totalchapters elements are removed from the book node and therefore not printed on the output screen.

No Comments