Seattle427
Seattle427

Reputation: 31

parse xml file and output to text file

Trying to parse an xml file (config.xml) with ElementTree and output to a text file. I looked at other similar ques here but none helped me. Using Python 2.7.9

import xml.etree.ElementTree as ET
tree = ET.parse('config.xml')
notags = ET.tostring(tree,encoding='us-ascii',method='text')
print(notags)

OUTPUT

Traceback (most recent call last):
File "./python_element", line 9, in <module>
notags = ET.tostring(tree,encoding='us-ascii',method='text')
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1126, in      tostring
ElementTree(element).write(file, encoding, method=method
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 814, in write
_serialize_text(write, self._root, encoding)
File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1005, in   _serialize_text
for part in elem.itertext():
AttributeError: 

> 'ElementTree' object has no attribute 'itertext'

Upvotes: 2

Views: 2136

Answers (1)

falsetru
falsetru

Reputation: 368894

Instead of tree (ElementTree object), pass an Element object. You can get an root element using .getroot() method:

notags = ET.tostring(tree.getroot(), encoding='utf-8',method='text')

Upvotes: 2

Related Questions