Remove nodes using XPathNodeIterator

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
To remove a set of nodes with the XPathNavigator class, when you have straight-forward XPath to select the nodes to delete, the Select method can help to accomplish the task. You might think that once you have an XPathNodeIterator with the nodes you want
to delete you can simply use the following code to delete them all.
<pre>Do While MyNodeIterator.MoveNext()

MyNodeIterator.Current.DeleteSelf()

Loop[/code]
<p style="margin:0in 0in 0pt <span style="font-size:small <span style="font-family:Calibri
<p style="margin:0in 0in 0pt <span style="font-size:small <span style="font-family:Calibri Unfortunately this will only delete a single node. The XPathNodeIterator can no longer move to the next node when the current has been deleted. I did a bit of searching
on the internet and found no XPathNavigator solutions to this problem. I was documenting another approach when it hit me that the XPathNodeIterator probably only has a problem with the current node being deleted. So I altered the example above as follows.
<p style="margin:0in 0in 0pt <span style="font-size:small <span style="font-family:Calibri
<div style="background-color:white; color:black
<pre>MyNodeIterator.MoveNext()

PreviousNav = MyNodeIterator.Current.CreateNavigator()



Do While MyNodeIterator.MoveNext()

PreviousNav.DeleteSelf()

PreviousNav = MyNodeIterator.Current.CreateNavigator()

Loop



PreviousNav.DeleteSelf()

[/code]

<p style="margin:0in 0in 0pt
<p style="margin:0in 0in 0pt With this solution the code is always deleting the node that was previously current. This may have been obvious to some, but it really did not come naturally to me.
<p style="margin:0in 0in 0pt
<p style="margin:0in 0in 0pt I hope that this helps someone going through the same frustration that I was having.
<p style="margin:0in 0in 0pt
<p style="margin:0in 0in 0pt Casey<br/>

<br/>

View the full article
 
Back
Top