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).
Related videos on Youtube
Author by
chirna
Updated on September 18, 2022Comments
-
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 over 10 yearsWhat version of ubuntu are you using?
-
chirna over 10 yearsthat was one of the file i found on net, I'm just trying to execute it, errors are coming as mentioned earlier..
-
franzlorenzon over 10 yearsIn my ubuntu 12.04 everything works correctly
-
chirna over 10 yearsI'm currently using 12.0.4
-
franzlorenzon over 10 yearswhat's the output of
ls -l /usr/lib/python2.7/xml
? -
Jeffrey Irudayaraj over 10 yearsHmm works like a charme here? Are you sure that the elementtree module is installed? I have Python 2.7.3.
-
franzlorenzon over 10 yearsHow have you named your script? It could be important (stackoverflow.com/questions/3073033/…)
-
belacqua over 10 yearsI don't have problems with 2.7 on Ubuntu 13.04. As a workaround, try
sudo pip install elementtree
-
belacqua over 10 years
-
-
franzlorenzon over 10 yearsIf you want to thank me even more, upvote my answer :) have a good day! ;)