2012-09-19 63 views
4

在我的python代碼中,我試圖以XML格式顯示輸出。爲此,我使用了XMLwriterImportError:No module named elementtree.SimpleXMLWriter

但它顯示錯誤:

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() 
+0

你需要安裝[elementtree工具包](http://effbot.org/zone/xml-writer.htm)我估計。 – tuxuday

+0

是在您的環境中安裝的''elementtree''模塊? –

+0

你正在使用哪個版本的python?此錯誤表明您沒有安裝元件樹。這是哪個操作系統? – Oz123

回答

1

我不是嚮導與XML,但是,它看起來像你要麼安裝elementtree(顯然SimpleXMLWriter wasn't included in 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()寫這個。

reference1

reference2

2

發運與Python 2.5和最多不包括SimpleXMLWriter模塊ElementTree模塊;後者與ElementTree功能的其餘部分完全分開。

要生成XML,我個人使用了模板語言,如Chameleon。您也可以使用ElementTree API本身構建樹,並簡單地對結果調用.write()