"ason" <sc******@inode-dot-at.no-spam.invalid> wrote in message news:41********@Usenet.com...
I just tried to replace a single XmlNode with several ChildNodes.
When doing this with the following code i found out that if you get
the ChildNodes with 'ChildNodes' - property the nodes get removed. Is
this possibly a Framework Bug??
No, it's a bug in the code example.
foreach( XmlNode node in oldNode.ChildNodes )
{
newNode.AppendChild( node );
}
parent.ReplaceChild( newNode, oldNode );
There are two important facts to realize about this code:
1. foreach uses an IEnumerator. Therefore, if you change the
collection being enumerated, you're going to invalidate the loop's
iterator and it will stop after making the first pass through the
loop's body.
2. XmlNodes have only one ParentNode. When you call AppendChild
you're changing the ParentNode of what was formerly a child node
of oldNode. This means oldNode has one less ChildNode, and new-
Node has one more (i.e., ChildNodes has changed).
After doing several Tests is tried it the following way and it worked
fine.
[code:1:f2d0f1e03d]
for( int i = 0; i < oldNode.ChildNodes.Count; i++ )
{
XmlNode node = oldNode.ChildNodes[ i ];
newNode.AppendChild( node );
i--;
}
parent.ReplaceChild( newNode, oldNode );
[/code:1:f2d0f1e03d]
Did you notice you're incrementing 'i' and then decrementing 'i'
to make this work (again, because the main factor is Append-
Child( ) alters the membership of ChildNodes)?
IEnumerator operates over an IEnumerable, which iterates in
a forward-only manner (IEnumerable has only three members:
Current, MoveNext( ) and Reset( )). As such, a foreach state-
ment can't be expected to go back/forth as you've done in the
for loop above.
Derek Harmon