Hi!
I wanted to select a subset of nodes (list =
selectNodes("parent/child[foo='bar']") from a XmlDocument, then remove all
(parentNode.removeAll();) child-nodes and insert the previous selected nodes
back. Of course the XmlNodes in the nodelist ref. where lost once the
removeAll() were executed, this is expected.
So the obvious way to achive the result would be to clone the nodes or
remove the nodes not qualifying the Xpath.
Well I belive I have found an, for me, unexpected shortcut. If I refer the
list.count property prior to removeAll(), the nodes is still referable and
can be inserted back.
The explanation for this is, as understad it, is that XmlNodeList.Count is a
heap based data type, Integer, and therefore addRef+1 to all selected nodes
when .Count is executed, and therefore they are not marked as collectable.
I've tried searching comments on this one but found nothing. Well, maybe
it's just me that belive this particular behaviour of XmlDocument is
remarkable?
Please comment or correct me, regards,
Markus
P.o.c. (Winform/C#)
XmlDocument doc = new XmlDocument();
doc.LoadXml("<parent><child><foo>bar</foo></child><child><foo>bar</foo></child><child><foo>not bar</foo></child></parent>");
XmlNodeList list = doc.SelectNodes("parent/child[foo='bar']");
MessageBox.Show("Nr. of childs before removeAll()= "+
doc.SelectNodes("parent/child").Count.ToString());
// Remove the comments on the line below to keep nodes in nodelist referable
//int c = list.Count;
doc.SelectSingleNode("parent").RemoveAll();
MessageBox.Show("Nr. of childs after removeAll()= "+
doc.SelectNodes("parent/child").Count.ToString());
foreach(XmlNode item in list)
doc.SelectSingleNode("parent").AppendChild(item);
MessageBox.Show("Nr. of childs after appending list= "+
doc.SelectNodes("parent/child").Count.ToString());