微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python从xmlns解析二进制文档并保存到本地

如何解决Python从xmlns解析二进制文档并保存到本地

所以我收到了这样的请求调用的响应:

resourceType": "Binary","id": "07a6483f-732b-461e-86b6-edb665c45510","contentType": "application/msword","content": "UEsDBBQA.......

它在我的代码显示为:

b'<Binary xmlns="http://hl7.org/fhir">\r\n   <id value="07a6483f-732b-461e-86b6-edb665c45510"></id>\r\n   <contentType value="application/msword"></contentType>\r\n   <content value="UEsDBBQ

我需要提取内容值并另存为,在本例中为 Word 文档。我尝试过基于拆分和使用 ElementTree 的解决方案,但我似乎无法解析内容并将其保存为 word 文件

现在就这样做:

with open('/tmp/Metadata.doc','wb') as f:
    f.write(response.content

结果是写了整篇文章,Word 会像这样打开:

enter image description here

有什么想法吗?提前致谢

解决方法

鉴于 response.content 是一个字符串变量,可以使用 ElementTree 解析 XML:

from xml.etree import ElementTree as etree

# declare namespace
ns = {'ns': 'http://hl7.org/fhir'}
# parse XML
tree = etree.fromstring(response.content)
# find content element considering namespace
content_element = tree.find('.//ns:content',ns)
# extract attribute "value"
content = content_element.get('value')
# save content to file

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。