When working with XML today, a batch loop is used to delete nodes. The problem is that the loop is not over and the program jumps out of the loop. It took a long time to figure it out.
Pre-resolved code:
XmlNodeList items = xn. ChildNodes; Gets the node list//delete all nodes for (int i = 0; i < items. Count; i++) { XmlElement page = (XmlElement) items[0]; Xn. RemoveChild (page); }
Because each time the loop is removed, the node is deleted after the item. The value of Count will be-1.
If the current item. Count is 5,i=1, the first loop count (5) -1=4, then this time the i++ is 2, the second time count (4)-1 is 3, and i++ is 3, so meet the conditions I<count, so exit the loop. This causes the entire node to not fully traverse the XML file, so it jumps out of the loop.
Of course you use foreach (XmlNode in item. Count) is not a good idea either.
Solutions are:
int len = items. Count; for (int i = 0; i < len; i++) { XmlElement page = (XmlElement) items[0]; Xn. RemoveChild (page); }