Python: error during generation of XML file from python dictionary

5,800

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:
5,800

Related videos on Youtube

chirna
Author by

chirna

Updated on September 18, 2022

Comments

  • chirna
    chirna over 1 year
    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?

    • franzlorenzon
      franzlorenzon over 10 years
      What version of ubuntu are you using?
    • chirna
      chirna over 10 years
      that was one of the file i found on net, I'm just trying to execute it, errors are coming as mentioned earlier..
    • franzlorenzon
      franzlorenzon over 10 years
      In my ubuntu 12.04 everything works correctly
    • chirna
      chirna over 10 years
      I'm currently using 12.0.4
    • franzlorenzon
      franzlorenzon over 10 years
      what's the output of ls -l /usr/lib/python2.7/xml?
    • Jeffrey Irudayaraj
      Jeffrey Irudayaraj over 10 years
      Hmm works like a charme here? Are you sure that the elementtree module is installed? I have Python 2.7.3.
    • franzlorenzon
      franzlorenzon over 10 years
      How have you named your script? It could be important (stackoverflow.com/questions/3073033/…)
    • belacqua
      belacqua over 10 years
      I don't have problems with 2.7 on Ubuntu 13.04. As a workaround, try sudo pip install elementtree
    • belacqua
      belacqua over 10 years
  • franzlorenzon
    franzlorenzon over 10 years
    If you want to thank me even more, upvote my answer :) have a good day! ;)