def replace(self, eid, replacement, index=0):
        """
        Replace an xml element marked with the matching eid. If the replacement value is an Element or TextElement,
        it's swapped in untouched. If it's a Template, the children of the root element in the template are used.
        Otherwise the replacement value is wrapped with a TextElement.
        """
        if eid in self.__element_ids:
            elems = self.__element_ids[eid]
        elif eid in self.__repeat_ids:
            elems = self.__repeat_ids[eid]
        else:
            return

        if index < len(elems):
            elem = elems[index]
            current_pos = elem.parent.children.index(elem)
            elem.parent.children.remove(elem)
            replacement_type = type(replacement)
            if replacement_type in (Element, TextElement):
                self.check_element(replacement, True)
                elem.parent.children.insert(current_pos, replacement)
                replacement.parent = elem.parent
            elif replacement_type == Template:
                for child in replacement.root.children:
                    elem.parent.children.insert(current_pos, child)
                    child.parent = elem.parent
                    current_pos += 1
                self.__merge_ids(self.__element_ids, replacement.__element_ids)
                self.__merge_ids(self.__attrib_ids, replacement.__attrib_ids)
                self.__merge_ids(self.__repeat_ids, replacement.__repeat_ids)
            else:
                elem.parent.children.insert(current_pos, TextElement(replacement))
Replace an xml element marked with the matching eid. If the replacement value is an Element or TextElement,
        it's swapped in untouched. If it's a Template, the children of the root element in the template are used.
        Otherwise the replacement value is wrapped with a TextElement.