我需要将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'
最佳答案
您正在将已创建的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字符集以外的文本的文档都将失败。关于python - 将xml输出到控制台(xml.etree.ElementTree),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25428751/