ImportError: no module named elementtree.SimpleXMLWriter

In my Python code, I am trying to display the output in XML format. For this purpose I use XMLwriter .

But it shows an error:

 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 

The line that causes the error:

 from elementtree.SimpleXMLWriter import XMLWriter 

All my python code:

 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
source share
2 answers

The ElementTree module shipped with Python 2.5 and later does not include the SimpleXMLWriter module; the latter is completely separate from the rest of the ElementTree functions.

To create XML, I personally use a template language such as Chameleon . You can also build a tree using the ElementTree API itself and simply call .write() for the result.

+2
source

I'm not a master with XML, but it looks like you either need to install elementtree (obviously SimpleXMLWriter was not included in python2.5 ... and maybe it was never embedded in the standard library) or use the tools in the standard library.

For me it looks something like this:

 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]) 

Then you can write this with root.write() .

reference1

reference2

+1
source

Source: https://habr.com/ru/post/1435044/


All Articles