1

After sending a request to a webserver in python, I received XML code and I applied few changes on it

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

output : "Msg":"MobileNo Already Exists"

I need a more efficient way to convert XML result into an array, so that print(j[“Msg”]) would give result MobileNo Already Exists

1
  • There is a module for XML in Python: docs.python.org/3/library/… Combine this with the JSON library (import json and json.loads(some_string)), as your string contains JSON nested in XML. Commented Jul 21, 2020 at 17:36

2 Answers 2

2

There is a module for XML in Python: minidom Combine this with the JSON library, as your string contains JSON nested in XML:

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"))
Sign up to request clarification or add additional context in comments.

Comments

0

Another method. This library uses regex implementation.

import json
from simplified_scrapy import SimplifiedDoc
html = '<?xml version="1.0" encoding="utf-8"?><string xmlns="http://emts.erpguru.in/">{"data":[{"Id":0,"IsSuccess":true,"Msg":"MobileNo Already Exists"}] }</string>'

doc = SimplifiedDoc(html)
s = doc.string.html
# Or
s = doc.select('string').html
result = json.loads(s)
print (result["data"][0]["Msg"])

Result:

MobileNo Already Exists

Here are more examples: https://github.com/yiyedata/simplified-scrapy-demo/tree/master/doc_examples

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.