def untlxml2py(untl_filename):
    """Parse a UNTL XML file object into a pyuntl element tree.

    You can also pass this a string as file input like so:
    import StringIO
    untlxml2py(StringIO.StringIO(untl_string))
    """
    # Create a stack to hold parents.
    parent_stack = []
    # Use iterparse to open the file and loop through elements.
    for event, element in iterparse(untl_filename, events=('start', 'end')):
        if NAMESPACE_REGEX.search(element.tag, 0):
            element_tag = NAMESPACE_REGEX.search(element.tag, 0).group(1)
        else:
            element_tag = element.tag
        # Process the element if it exists in UNTL.
        if element_tag in PYUNTL_DISPATCH:
            # If it is the element's opening tag,
            # add it to the parent stack.
            if event == 'start':
                parent_stack.append(PYUNTL_DISPATCH[element_tag]())
            # If it is the element's closing tag,
            # remove element from stack. Add qualifier and content.
            elif event == 'end':
                child = parent_stack.pop()
                if element.text is not None:
                    content = element.text.strip()
                    if content != '':
                        child.set_content(element.text)
                if element.get('qualifier', False):
                    child.set_qualifier(element.get('qualifier'))

                # Add the element to its parent.
                if len(parent_stack) > 0:
                    parent_stack[-1].add_child(child)
                # If it doesn't have a parent, it is the root element,
                # so return it.
                else:
                    return child
        else:
            raise PyuntlException(
                'Element "%s" not in UNTL dispatch.' % (element_tag)
            )
Parse a UNTL XML file object into a pyuntl element tree.

    You can also pass this a string as file input like so:
    import StringIO
    untlxml2py(StringIO.StringIO(untl_string))