尝试使用ElementTree解析xml文件(config.xml)并输出到文本文件。我在这里看了其他类似的问题,但没有人帮助我。使用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)
输出
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'
答案 0 :(得分:2)
而不是tree
(ElementTree
对象),传递Element
对象。您可以使用.getroot()
方法获取根元素:
notags = ET.tostring(tree.getroot(), encoding='utf-8',method='text')