im building a site(flask) and making using a payment api but its my first time using api and i have no clue how get the variables from xml
Here is the xml that return from request
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="API_Library">
<SOAP-ENV:Body>
<ns1:gerarReferenciaMBResponse>
<sucesso>true</sucesso>
<entidade>82142</entidade>
<referencia>000762738</referencia>
<valor>5</valor>
<estado>0</estado>
<resposta>OK</resposta>
</ns1:gerarReferenciaMBResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
And my request look like this
import requests
url = "https://sandbox.***.pt/****/api/api.php?wsdl=replica.*****.wsdl"
payload = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="API_Library">
<soapenv:Header/>
<soapenv:Body>
<api:gerarReferenciaMB>
<valor>5</valor>
<chave>****</chave>
<id>1</id>
<!--Optional:-->
<admin_callback>0</admin_callback>
<!--Optional:-->
<token>0</token>
<!--Zero or more repetitions:-->
<campos_extra>
<id>0</id>
<valor>0</valor>
</campos_extra>
<!--Optional:-->
<per_dup>0</per_dup>
<!--Optional:-->
<testa_pagamento>1</testa_pagamento>
</api:gerarReferenciaMB>
</soapenv:Body>
</soapenv:Envelope>"
headers = {
'Content-Type': 'text/xml'
}
response = requests.request("POST", url, headers=headers, data=payload)
My question is how is suppose to me to get the " and " values to set variables.
CodePudding user response:
I just found how to get it:
for item in a.split("</entidade>"):
if "<entidade>" in item:
print(item[item.find("<entidade>") len("<entidade>"):])
for item in a.split("</referencia>"):
if "<referencia>" in item:
print(item[item.find("<referencia>") len("<referencia>"):])
This will print whats between tags
CodePudding user response:
Try the below - it will create a python dict that contains the data you are looking for
import xml.etree.ElementTree as ET
xml = '''<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="API_Library">
<SOAP-ENV:Body>
<ns1:gerarReferenciaMBResponse>
<sucesso>true</sucesso>
<entidade>82142</entidade>
<referencia>000762738</referencia>
<valor>5</valor>
<estado>0</estado>
<resposta>OK</resposta>
</ns1:gerarReferenciaMBResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'''
root = ET.fromstring(xml)
elements = ['entidade','referencia']
data = {ele.tag: ele.text for ele in list(list(root)[0][0]) if ele.tag in elements}
print(data)
output
{'entidade': '82142', 'referencia': '000762738'}