def replace_xml_node_with_text(node, text):
    """There are some complications w/ lxml when determining where to add the
    replacement text. Account for all of that here."""
    parent, prev = node.getparent(), node.getprevious()
    if prev is not None:
        prev.tail = (prev.tail or '') + text
    else:
        parent.text = (parent.text or '') + text
    parent.remove(node)
