python - 如何通过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 那样有漏洞。
解决方案
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')
推荐阅读
- algorithm - 将循环计数器减半时的时间复杂度
- r - R-to-L 语言的控制台输出对齐(例如阿拉伯语)
- c# - 检索所有选定的项目checkcombbox c#
- android - Google Play 管理中心:将应用从 Alpha 升级到 Beta,但仍需要预先注册
- html - 如何在wijmo网格行之间设置间距
- c# - 如何从 asp.net web api 中的身份声明中获取经过 JWT 身份验证的登录用户
- mysql - 选择查询需要更多执行时间
- html - 尝试使用垂直居中的文本创建圆圈并且存在圆圈下的文本
- swift - I don't know where to define removeFromSuperview () for memory leak countermeasures when implementing addSubview with viewDidLoad
- android - 适用于 Android 和 iOS 的开放式街道地图