python - 从xml代码中提取数据并将其转换为python中的数组
问题描述
在 python 中向网络服务器发送请求后,我收到了 XML 代码,并对其进行了一些更改
import re
s='<?xml version="1.0" encoding="utf-8"?><string xmlns="http://emts.erpguru.in/">{"data":[{"Id":0,"IsSuccess":true,"Msg":"MobileNo Already Exists"}] }</string>'
result = re.search('"data":\[{(.*?)}', s)
j= (result.group(1)).split(',')
print(j[2])
输出 :"Msg":"MobileNo Already Exists"
我需要一种更有效的方法将 XML 结果转换为数组,这样
print(j[“Msg”])
就可以得到结果
MobileNo Already Exists
解决方案
Python 中有一个 XML 模块:minidom
将其与 JSON 库结合使用,因为您的字符串包含嵌套在 XML 中的 JSON:
import json
from xml.dom.minidom import parseString
s = '<?xml version="1.0" encoding="utf-8"?><string xmlns="http://emts.erpguru.in/">{"data":[{"Id":0,"IsSuccess":true,"Msg":"MobileNo Already Exists"}] }</string>'
dom = parseString(s)
json_string = dom.firstChild.firstChild.nodeValue
j = json.loads(json_string)
print(j["data"][0].get("Msg"))
推荐阅读
- python - 为什么在外部执行 Python 文件时会出现“NameError: name not defined”?
- azure - 获取正在运行的 Kubernetes Pod 内存中的文件列表
- python - 在使用 python 进行网络抓取时,是否有任何直接的方法可以从输出中删除 \xa0
- function - 用递归函数替换lool
- php - Phpmailer oauth2 - 需要专家
- angular - 在 Azure App Service 下运行的远程调试 Angular
- android - Flutter:使用带有 BottomNavigationBar 的可扩展文本字段
- mysql - mysql docker容器启动时laravel迁移数据库
- configuration - Nagiosgraph:为单个服务检查设置对数刻度
- reactjs - 如何使用 Nginx 在不同的 url 上运行两个 js 应用程序?