2012-04-04 79 views
-1

我试图使用Python和LXML从Mysql查询结果创建XML文件。这是我想要的格式。使用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() 

回答

2

这里有一个如何使用lxml构建xml的例子。

创建元素创建辅助函数很有用,这是一个简单的方法。为了演示目的,我创建了一个虚拟光标对象。

from lxml import etree 
from lxml.builder import E as buildE 

class DummyCursor(object): 
    def __init__(self,fields,rows=5): 
    self.description = [[f] for f in fields] 
    self.data = [ ["%s%02d" % (f,i) for f in fields] for i in range(rows) ] 
    def fetchall(self): 
    return self.data 

def E(tag,parent=None,content=None): 
    """Simple E helper""" 
    element = buildE(tag) 
    if content is not None: 
    element.text = unicode(content) 
    if parent is not None: 
    parent.append(element) 
    return element 

def fetchXML(cursor): 
    fields = [x[0] for x in cursor.description ] 
    doc = E('data') 
    for record in cursor.fetchall(): 
    r = E('row',parent=doc) 
    for (k,v) in zip(fields,record): 
     E(k,content=v,parent=r) 
    return doc 

doc = fetchXML(DummyCursor(['name','description'])) 

print etree.tostring(doc,pretty_print=True) 

产量:

<data> 
    <row> 
    <name>name00</name> 
    <description>description00</description> 
    </row> 
    <row> 
    <name>name01</name> 
    <description>description01</description> 
    </row> 
    <row> 
    <name>name02</name> 
    <description>description02</description> 
    </row> 
    <row> 
    <name>name03</name> 
    <description>description03</description> 
    </row> 
    <row> 
    <name>name04</name> 
    <description>description04</description> 
    </row> 
</data> 
+0

我无法移植到我的你的榜样。具体将内容放入标签 – user1130161 2012-04-04 15:36:48

+0

我还没有得到MySQL方便。如果'fetchall'返回的每行都不是一个值序列,那么你需要把这行变成一系列值。另外,您可能需要充实E helper类以将非字符串内容值呈现为字符串 – MattH 2012-04-04 15:39:46

+0

我已将修改助手以unicode传递的内容参数。例如,您可能想根据模式将布尔值表示为小写字母,以便您可以更改帮助程序以将布尔值呈现为小写字母。 – MattH 2012-04-04 15:46:07