首页 > 解决方案 > 从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

标签: pythonarraysxml

解决方案


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"))

推荐阅读