When you work with XML documents loaded into an XmlDocument class, you often need to examine the contents of child nodes. The XMLDOM programming interface purposedly provides the ChildNodes property. In the .NET XmlDocument class, ChildNodes returns an internal object of type XmlChildNodes. (The object is not documented, but you can easily verify this claim by simply checking the type of the object that ChildNodes returns.)
XmlChildNodes is not a true collection. It is implemented as a linked list and does not cache any information. What does this mean to you?
For example, when you access the Count property to know how many children a given node has, the object returned by ChildNodes scrolls the entire list to count the number of nodes on the fly. When you ask for a particular node through the Item property, the list is scanned from the beginning until a matching node is found.
Scrolling forward through the list of child nodes is fast and effective. The same cant be said for backward scrolling. The list of nodes is not double-linked, and each node doesnt also store a pointer to the previous one in the list. For this reason, the previous sibling is reached by walking through the list from the beginning to the node that precedes the current one.
To summarize, when you are processing XML subtrees, try to minimize calls to PreviousSibling, Item, and Count because they always walk through the entire collection of subnodes to get their expected output. Whenever possible, design your code to take advantage of forward-only movements and perform them using NextSibling.
Source:
Applied XML Programming for Microsoft .NET, Dino Esposito, Microsoft Press 2002
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible.
Submit your tip here.