Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.
ImportError: No module named elementtree.SimpleXMLWriter      

The code:

import xml.etree.cElementTree as ET 

root = ET.Element("root") 
doc = ET.SubElement(root, "doc") 
field1 = ET.SubElement(doc, "field1") 
field1.set("name", "blah") 
field1.text = "some value1" 
field2 = ET.SubElement(doc, "field2") 
field2.set("name", "asdfasd") 
field2.text = "some vlaue2" 
tree = ET.ElementTree(root) 
tree.write("filename.xml") 

Can anyone help?

share|improve this question
    
What version of ubuntu are you using? –  franzlorenzon Sep 30 '13 at 9:00
    
that was one of the file i found on net, I'm just trying to execute it, errors are coming as mentioned earlier.. –  chirna Sep 30 '13 at 9:06
    
In my ubuntu 12.04 everything works correctly –  franzlorenzon Sep 30 '13 at 9:08
    
I'm currently using 12.0.4 –  chirna Sep 30 '13 at 9:09
    
what's the output of ls -l /usr/lib/python2.7/xml? –  franzlorenzon Sep 30 '13 at 9:15
show 4 more comments

1 Answer 1

up vote 0 down vote accepted

Edit: Have you named your script: xml.py? Change it and it should work.

As a workaround, you could use etree in the lxml package. If you don't have lxml installed, type:

sudo apt-get install python-lxml

And for the modified version of your program:

import lxml.etree as ET 

root = ET.Element("root") 
doc = ET.SubElement(root, "doc") 
field1 = ET.SubElement(doc, "field1") 
field1.set("name", "blah") 
field1.text = "some value1" 
field2 = ET.SubElement(doc, "field2") 
field2.set("name", "asdfasd") 
field2.text = "some vlaue2" 
tree = ET.ElementTree(root) 
tree.write("filename.xml") 

Output:

<root>
   <doc>
        <field1 name="blah">some value1</field1>
        <field2 name="asdfasd">some vlaue2</field2>
   </doc>
</root>

For differences between the two solutions, lxml.etree and ElementTree, have a look at this doc lxml.etree versus ElementTree.

cElementTree is slightly faster compared to lxml.etree, anyway the latter is still a fast xml parser written in C, and I think the difference is negligible (benchmarks here).

share|improve this answer
1  
thank u, its working.. –  chirna Oct 1 '13 at 6:01
    
If you want to thank me even more, upvote my answer :) have a good day! ;) –  franzlorenzon Oct 1 '13 at 7:00
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.