Creates an element named after elem_path, containing elem_txt, with kwargs
    as attributes, inserts it into elem_to_parse at elem_idx and returns it.

    If elem_path is an XPATH pointing to a non-existent element, elements not
    in the path are inserted and the text and index are applied to the last one.

    If elem_path is an XPATH pointing to an existing element, the new element is
    inserted as a sibling of the last one in the path at the index specified.

def insert_element(elem_to_parse, elem_idx, elem_path, elem_txt=u'', **attrib_kwargs):
    """
    Creates an element named after elem_path, containing elem_txt, with kwargs
    as attributes, inserts it into elem_to_parse at elem_idx and returns it.

    If elem_path is an XPATH pointing to a non-existent element, elements not
    in the path are inserted and the text and index are applied to the last one.

    If elem_path is an XPATH pointing to an existing element, the new element is
    inserted as a sibling of the last one in the path at the index specified.
    """

    element = get_element(elem_to_parse)

    if element is None or not elem_path:
        return None

    if not elem_idx:
        elem_idx = 0

    if elem_path and XPATH_DELIM in elem_path:
        tags = elem_path.split(XPATH_DELIM)

        if element_exists(element, elem_path):

            # Get the next to last element in the XPATH
            parent = get_element(element, XPATH_DELIM.join(tags[:-1]))

            # Insert the new element as sibling to the last one
            return insert_element(parent, elem_idx, tags[-1], elem_txt, **attrib_kwargs)

        else:
            this_elem = element
            last_idx = len(tags) - 1

            # Iterate over tags from root to leaf
            for idx, tag in enumerate(tags):
                next_elem = get_element(this_elem, tag)

                # Insert missing elements in the path or continue
                if next_elem is None:

                    # Apply text and index to last element only
                    if idx == last_idx:
                        next_elem = insert_element(this_elem, elem_idx, tag, elem_txt, **attrib_kwargs)
                    else:
                        next_elem = insert_element(this_elem, 0, tag, u'', **attrib_kwargs)

                this_elem = next_elem

            return this_elem

    subelem = Element(elem_path, attrib_kwargs)
    subelem.text = elem_txt

    element.insert(elem_idx, subelem)

    return subelem