我正在尝试使用 Python 和 LXML 从 Mysql 查询结果创建 XML 文件。这是我想要的格式。
<DATA>
<ROW>
<FIELD1>content</FIELD1>
<FIELD2>content</FIELD2>
</ROW>
</DATA>
由于某种原因,代码格式不正确,XML 将无法验证。这是那个代码
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()