tags:

views:

106

answers:

3

The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree

from xml.etree.ElementTree import ElementTree

...

tree = ElementTree()
node = ElementTree()

node = tree.parse(open("my_xml.xml"))
text = node.tostring()
A: 

The docs you've linked to do not support the existence of a ElementTree.tostring() method.

Also, your call to tree.parse() rebinds node.

Ignacio Vazquez-Abrams
+1  A: 

tostring() is actually a function of the ElementTree module not a method of the ElementTree wrapper class.

>>> import xml.etree.ElementTree as ET
>>> ET.fromstring('<xml><one>one</one></xml>')
>>> x     
<Element xml at 7f749572f710>
>>> ET.tostring(x)
'<xml><one>one</one></xml>'
Mark
+1  A: 

tostring is a method of the xml.etree.ElementTree module, not the confusingly similarly-named xml.etree.ElementTree.ElementTree class.

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import tostring

tree = ElementTree()
node = tree.parse(open("my_xml.xml"))
text = tostring(node)
John Kugelman
This code works. Thank you.
Alex