'Insert item into parent (or append if index is None), fixing
indentation. Only works with self closing items.'

def insert_into_xml(self, parent, item, index=None):

    if (index is None):
        parent.append(item)
    else:
        parent.insert(index, item)
    idx = parent.index(item)
    if (idx == 0):
        item.tail = parent.text
        if (len(parent) == 1):
            sibling = parent.getprevious()
            if (sibling is None):
                return
            parent.text = sibling.text
            item.tail = sibling.tail
    else:
        item.tail = parent[(idx - 1)].tail
        if (idx == (len(parent) - 1)):
            parent[(idx - 1)].tail = parent.text
