When operating XML today, nodes that do not meet the conditions are deleted after the subnodes of batch loop are used .. an error occurred .. it took more than an hour .. the problem is found ..
Let's take a look at the normalProgramHow to Implement/
1 For ( Int I = 0 ; I < Xndlist. Count; I ++ ) // Traverse nodes
2 {
3 Xmlelement XN = (Xmlelement) xndlist [I];
4 Xmlnode x_id = XN. selectsinglenode ( " ID " );
5 If (X_id.innertext ! = ID) // Delete the child nodes that meet the conditions
6 {
7Root. removechild (Xn );
8}
9 }
It is correct and reasonable .. but the effect is incorrect .. only a part of nodes can be deleted after the test .. so the breakpoint is broken again, observe and observe again .. finally found the problem .. there is a problem with the I value in the loop... because each cycle, after the node is deleted, xndlist. the value of count is-1,
For example, if my current count is 5, I = 1, and the first round of Count (5)-1 = 4, then I ++ is 2, in the second round, count (4)-1 is 3, and after I ++ is 3, the condition I <count is satisfied, and then the loop is exited .. this leads to the failure to completely traverse all nodes of the XML file, resulting in different results than we expected.
Of course, you cannot use foreach (xmlnode in xndlist. Count...
My final solution is: first determine the total number of nodes, Then loop COUNT = Total number of nodes, then after deleting the node, re-obtain the total number of nodes, and determine whether the total number of nodes is 0, if the value is 0, the loop is exited .. by doing so, we can ensure that the loop can completely traverse all the byte points and delete all the child nodes that meet the conditions .. specificCodeAs follows ..
1 Int Len = Xndlist. count; // Total number of defined nodes
2 For ( Int I = 0 ; I < Len; I ++ ) // The total number of cyclic nodes to ensure that the nodes can be traversed
3 {
4 Xmlelement XN = (Xmlelement) xndlist [ 0 ];
5 Xmlnode x_id = XN. selectsinglenode ( " ID " );
6 If (X_id.innertext ! = Friendid)
7 {
8Root. removechild (Xn );
9
10}
11 Int Xx = Xndlist. count; // Obtain the total number of nodes again to prevent node leakage.
12 If (Xx = 0 ) {//Exit if no subnode exists.
13Break;
14}
15 }
In fact, this problem is very similar to the first time I wrote a for loop. I remember this was the first time I wrote a loop:... if you have encountered a similar problem, please pay attention to it ..
For (INT I = 0; I <10; I ++) {// The intended output is 1-10
Response. Write (I );
I ++; // The result ignores the changes here.
}