4

在我的 python 代码中,我试图以 XML 格式显示输出。为此,我使用XMLwriter.

但它显示错误:

Traceback (most recent call last):
  File "C:\Users\Ponmani\Desktop\test.cgi", line 8, in <module>
    from elementtree.SimpleXMLWriter import XMLWriter
ImportError: No module named elementtree.SimpleXMLWriter

导致错误的行是:

from elementtree.SimpleXMLWriter import XMLWriter

我的整个python代码是:

import os
import cgi
import MySQLdb
import cgitb
from xml.etree.ElementTree import ElementTree
from elementtree.SimpleXMLWriter import XMLWriter
import sys
import SecureDb
cgitb.enable()
print "Content-type: text/xml\n\n";
root=xml.start("root")
conn= MySQLdb.connect(host = SecureDb.host ,user =SecureDb.user ,passwd=SecureDb.password ,db=SecureDb.database)
cursor=conn.cursor()
xml=XMLWriter(sys.stdout)
cursor.execute("select * from register where Name='Subburaj'")
result=cursor.fetchall()
if(result!=()):    
    for colns in result:
         xml.start("Group")
         xml.element("Name","%s" %(colns[0]))
         xml.element("Mail","%s" %(colns[1]))
print result
xml.end()
xml.close(root)
conn.commit()
cursor.close()
conn.close()
4

2 回答 2

3

ElementTreePython 2.5 及更高版本附带的模块包括该SimpleXMLWriter模块;后者与其他功能完全分开ElementTree

为了生成 XML,我个人使用模板语言,例如Chameleon。您还可以使用 ElementTree API 本身构建树并简单地调用.write()结果。

于 2012-09-19T11:39:08.297 回答
1

我不是 XML 的向导,但是,看起来您要么需要安装elementtree(显然 SimpleXMLWriter不包含在 python2.5 中......也许它从未被拉入标准库),或者使用这些设施在标准库中。

对我来说,它看起来像:

import xml.etree.ElementTree as ET
root = ET.Element('root')
#...

for colns in result:
     new_group = ET.SubElement(root,"Group")
     new_elem = ET.SubElement(new_group,"Name")
     new_elem.text = "%s" %(colns[0])
     #I suppose that:
     #ET.SubElement(new_group,"Name").text = str(colns[0])
     #would work too ...
     new_elem = ET.SubElement(new_group,"Mail")
     new_elem.text = "%s" %(colns[0])

然后,您可以使用root.write().

参考1

参考文献2

于 2012-09-19T11:36:43.023 回答