def insert_target_children(tree, xpath, namespaces, children, insertbefore,
    insertafter):
    """
    Insert the given children before or after the given xpath. If insertbefore is True, it is inserted before the
    first xpath hit, with insertafter, it is inserted after the last xpath hit.
    """
    insert_target = tree.xpath(xpath, namespaces=namespaces)
    loc_index = 0 if insertbefore else -1
    index_in_parent = insert_target[loc_index].getparent().index(insert_target
        [loc_index])
    parent = insert_target[0].getparent()
    if insertafter:
        index_in_parent += 1
    for child in children:
        parent.insert(index_in_parent, child)
        index_in_parent += 1
