import glob, exceptions
from lxml import etree


g = glob.glob("./*.xml")

for fileName in g:
    f = open(fileName)
    try:
        tree = etree.parse(f)
        rows = tree.findall('row')
        for row in rows:
            _fields = row.findall('field')
            dataList = []
            fieldList = []
            try:
                for _field in _fields:
                    fieldList.append(_field.get('name'))
                    try:
                        try:
                            text = _field.text.encode('ascii', 'xmlcharrefreplace').replace("'", "\\'")
                        except exceptions.AttributeError, e:
                            text = ''
                        value = ["'", text, "'"]
                        dataList.append(''.join(value))
                        fields = ','.join(fieldList)
                        values = ','.join(dataList)
                    except Exception, e:
                        print "Couldn't join either fields or values: %s" % e
                print 'INSERT INTO %s' % fileName.replace("/tmp/0/XON/curtis/", "").replace(".xml", ""),
                print '(%s) VALUES (%s);' % (fields, values)
            except Exception, e:
                print "%r, %s, %r" % (etree.tostring(row), e, _fields)
                
    except Exception, e:
        print "%s in file %s" % (e, fileName)
