I am trying to use Python and LXML to create an XML file from a Mysql query result. Here is the format I want.
<DATA>
<ROW>
<FIELD1>content</FIELD1>
<FIELD2>content</FIELD2>
</ROW>
</DATA>
For some reason the code isn't formatting right and the XML will not validate. Here is that code
from lxml import etree
from lxml.etree import tostring
from lxml.builder import E
import MySQLdb
try:
conn = MySQLdb.connect(host = 'host',user = 'user',passwd = 'pass',db = 'db')
cursor = conn.cursor()
except:
sys.exit(1)
cursor.execute("SELECT * FROM db.table")
columns = [i[0] for i in cursor.description]
allRows = cursor.fetchall()
xmlFile = open("mysqlxml.xml","w")
xmlFile.write('<DATA>')
for rows in allRows:
xmlFile.write('<ROW>')
columnNumber = 0
for column in columns:
data = rows[columnNumber]
if data == None:
data = ''
xmlFile.write('<%s>%s</%s>' % (column,data,column))
columnNumber += 1
xmlFile.write('</ROW>')
xmlFile.write('</DATA>')
xmlFile.close()
Here's a little example of how you can build xml using lxml.
It's useful to create a helper function for element creation, here's a simple one. I've created a dummy cursor object for demo purposes.
Yields: