Reasons for the failure of ASP. NET Bulk Delete XML node and its solution

Source: Internet
Author: User

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); }

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.