gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:42 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于python - 解析xml文件并输出到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36055297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com