tags:

views:

50

answers:

2

I believe I have found a weird bug as follow:

I want to delete the first two nodes in an XmlNodeList.

I know that there may be other ways of doing this (there surely are) but it is the reason why one of the code segments works and one doesn't (the difference being the Count line) that I am interested in.

var strXml = @"<food><fruit type=""apple""/><fruit type=""pear""/><fruit type=""banana""/></food>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXml);

XmlNodeList nlFruit = doc.SelectNodes("food/fruit");
for(int i = 0; i < 2; i++)
{
    // This produces a null reference exception:
    nlFruit[i].ParentNode.RemoveChild(nlFruit[i]);
}

However, if I count the number of nodes in the XmlNodeList it works and I am left with the desired outcome:

var strXml = @"<food><fruit type=""apple""/><fruit type=""pear""/><fruit type=""banana""/></food>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXml);

XmlNodeList nlFruit = doc.SelectNodes("food/fruit");
// Count the nodes..
Debug.WriteLine(nlFruit.Count);
for(int i = 0; i < 2; i++)
{
    nlFruit[i].ParentNode.RemoveChild(nlFruit[i]);
}

// doc is now: <food><fruit type="banana" /></food>
A: 

Both are wrong you should delete from the end

for(int i = 1; i >= 0; i--)
{
    nlFruit[i].ParentNode.RemoveChild(nlFruit[i]);
}

because you remove the 0 th element, and 1 st element becomes the 0 th, than you removes 1st element which is null.

ArsenMkrt
What do you mean by "wrong"? Perhaps I should have clarified; I just want to delete the first X nodes in an XmlNodeList. The second example works by the way and results in the XmlDocument containing just the Banana
Gus F
try my version without counting the nodes, is it works?
ArsenMkrt
Yes, your version works, thanks for your answer, but that is not the point of the question. The question relates to why counting the nodes (line 7 of the 2nd code segment) makes any difference to the two code segments I posted.
Gus F
I got the point, you are doing wrong thing in both cases and the result is side effect, In both cases this should fail, but somehow it works in the second case, I don't know why, I guess it depends from inner state of class and there is no logic...
ArsenMkrt
It is not valid action to remove from list from the beginning, and it may cause unexpected results...
ArsenMkrt
Thanks - it is bizarre though.. I know that lists should have items removed with a decreasing counter, just thought it was odd that counting XmlNodeList made it appear to work ok!
Gus F
A: 

May be this will help:

Halloween Problem : http://blogs.msdn.com/mikechampion/archive/2006/07/20/672208.aspx

JayD