'XML Element tree import method
@param r: the S3Request method
@param attr: controller attributes'

@staticmethod
def put_tree(r, **attr):

    get_vars = r.get_vars
    if ('ignore_errors' in get_vars):
        ignore_errors = True
    else:
        ignore_errors = False
    def findnames(get_vars, name):
        nlist = []
        if (name in get_vars):
            names = get_vars[name]
            if isinstance(names, (list, tuple)):
                names = ','.join(names)
            names = names.split(',')
            for n in names:
                if ((n[0] == '(') and (')' in n[1:])):
                    nlist.append(n[1:].split(')', 1))
                else:
                    nlist.append([None, n])
        return nlist
    filenames = findnames(get_vars, 'filename')
    fetchurls = findnames(get_vars, 'fetchurl')
    source_url = None
    s3 = current.response.s3
    json_formats = s3.json_formats
    csv_formats = s3.csv_formats
    source = []
    representation = r.representation
    if ((representation in json_formats) or (representation in csv_formats)):
        if filenames:
            try:
                for f in filenames:
                    source.append((f[0], open(f[1], 'rb')))
            except:
                source = []
        elif fetchurls:
            import urllib
            try:
                for u in fetchurls:
                    source.append((u[0], urllib.urlopen(u[1])))
            except:
                source = []
        elif (r.http != 'GET'):
            source = r.read_body()
    elif filenames:
        source = filenames
    elif fetchurls:
        source = fetchurls
        source_url = fetchurls[0][1]
    elif (r.http != 'GET'):
        source = r.read_body()
    if (not source):
        if (filenames or fetchurls):
            r.error(400, 'Invalid    source')
        else:
            return r.get_struct(r, **attr)
    stylesheet = r.stylesheet(method='import')
    if (r.method == 'create'):
        _id = None
    else:
        _id = r.id
    if ('xsltmode' in get_vars):
        args = dict(xsltmode=get_vars['xsltmode'])
    else:
        args = dict()
    if source_url:
        args['source_url'] = source_url
    if ('data_field' in get_vars):
        args['data_field'] = get_vars['data_field']
    if ('image_field' in get_vars):
        args['image_field'] = get_vars['image_field']
    if (representation in json_formats):
        representation = 'json'
    elif (representation in csv_formats):
        representation = 'csv'
    else:
        representation = 'xml'
    try:
        output = r.resource.import_xml(source, id=_id, format=representation, files=r.files, stylesheet=stylesheet, ignore_errors=ignore_errors, **args)
    except IOError:
        current.auth.permission.fail()
    except SyntaxError:
        e = sys.exc_info()[1]
        if hasattr(e, 'message'):
            e = e.message
        r.error(400, e)
    return output
