解析xml文件并输出到文本文件

时间:2016-03-17 08:37:12

标签: python xml lxml

尝试使用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'

1 个答案:

答案 0 :(得分:2)

而不是treeElementTree对象),传递Element对象。您可以使用.getroot()方法获取根元素:

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