我需要将xml打印到我从响应中收到的控制台:
import xml.etree.ElementTree as ET
xml = req.text
result = ET.ElementTree(ET.fromstring(xml))
rough_string = ET.tostring(result, "utf-8")
reparsed = minidom.parseString(rough_string)
print reparsed.toprettyxml(indent="\t")
错误:
AttributeError: 'ElementTree' object has no attribute 'tag'
File "....", line x, in ...
rough_string = ET.tostring(result, "utf-8")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1126, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 820, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 900, in _serialize_xml
tag = elem.tag
AttributeError: 'ElementTree' object has no attribute 'tag'
答案 0 :(得分:7)
您正在将已创建的ElementTree对象传递回ElementTree:
result = ET.ElementTree(ET.fromstring(xml))
不要那样做;删除那里的ET.ElementTree()
电话:
result = ET.fromstring(xml)
现在,您的ET.tostring()
电话可以正常运行。
接下来,我看到您正在使用req.text
作为XML的源代码;如果那是requests
响应对象,那么传入的错误的值,您应该使用req.content
。 XML解析器应该传递字节字符串,而不是unicode
值。然后,解析器将根据XML声明进行解码。它可能适用于只包含ASCII文本的文档,但包含ASCII字符集之外的文本的任何内容都将失败。