Make register_named_element more efficient

This improves the code written for #1822 to use a single linear traversal.

The current code uses a binary search with `CompareDocumentPosition()` for comparing element position, however this method internally calls `traverse_preorder()` (i.e. a linear traversal) so calling this on every pass is quite inefficient.