首页 > 解决方案 > 如何通过defusedxml从AWS SQS API字节xml字符串响应中读取所有行,而不仅仅是第一行?

问题描述

代码:

from defusedxml import ElementTree as etree
s = b'<?xml version="1.0"?><GetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><GetQueueAttributesResult><Attribute><Name>ApproximateNumberOfMessages</Name><Value>2</Value></Attribute></GetQueueAttributesResult><ResponseMetadata><RequestId>xxxx</RequestId></ResponseMetadata></GetQueueAttributesResponse>'
print(etree.fromstring(s))

预期输出:
应显示完整的 xml 数据(与输入相同),以便进一步解析。

实际输出:
仅显示第一行。

<Element '{http://queue.amazonaws.com/doc/2012-11-05/}GetQueueAttributesResponse' at 0x09B50720>

这是它读取的所有数据。
因为我在这个输出上尝试了类似findall()and的函数getchildren(),但它没有进一步返回。

如何解决这个问题?或者如果有类似方法的替代库,请提出建议。

或者,如果有任何库可以将此类 xml 数据直接转换为json/dict,那将非常有帮助。
但是,它应该将数据转换为可读的形式,而不是像xmltodict它给出奇怪的地方那样OrderedDicts

注意:建议的任何库也需要安全,而不是像 xml 那样有漏洞。

标签: pythonjsonxmlamazon-web-servicesamazon-sqs

解决方案


from defusedxml import ElementTree as etree
tree = etree.parse('file.xml')
root = tree.getroot()
# gives the below output
   <Element '{http://queue.amazonaws.com/doc/2012-11-05/}GetQueueAttributesResponse' at 0x1107c7b88>
root.findall('.//{http://queue.amazonaws.com/doc/2012-11-05/}Attribute')
# gives the below output
   [<Element '{http://queue.amazonaws.com/doc/2012-11-05/}Attribute' at 0x1107c7c28>]

但我必须将 xml 保存为文件。

内联 xml 更新:与将文件另存为单独文件时的工作方式相同。

s = b'<?xml version="1.0"?><GetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><GetQueueAttributesResult><Attribute><Name>ApproximateNumberOfMessages</Name><Value>2</Value></Attribute></GetQueueAttributesResult><ResponseMetadata><RequestId>xxxx</RequestId></ResponseMetadata></GetQueueAttributesResponse>'
etree.fromstring(s).findall('.//{http://queue.amazonaws.com/doc/2012-11-05/}Attribute')

参考: 使用元素树 findall 解析 XML 命名空间


推荐阅读