I am hitting an api link with the code below:
import requests
url="https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/items/web.config?versionType=Branch&versionOptions=None"
data=requests.get(url=url, headers=headers)
The sample response:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MyApp.exe"
stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout"
hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
<PropertyGroup>
<EnvironmentName>Development</EnvironmentName>
</PropertyGroup>
I want to parse the api response to xml and extract the EnvironmentName, that is Development from this xml. Please assist
CodePudding user response:
you could achive this by simple searching in the string, like this
import re
result = re.search('<EnvironmentName>;(.*)</EnvironmentName>', response)
or by searching up a lib that can turn the response into an object and then iterating through its keys
CodePudding user response:
I am listing two packages that can be used to solve your problem.
I have used a free online sample XML API
to test your problem and write relevant code.
This library needs to be downloaded which can be done via pip in the following way pip install xmltodict
resp = requests.get('http://restapi.adequateshop.com/api/Traveler?page=6')
dict_of_xml = xmltodict.parse(resp.content)
You will get an output like this.
OrderedDict([('Travelerinformation', [OrderedDict([('id', '776'), ('name', 'Yaamini Yaamini'), ('email', '[email protected]'), ('adderes', 'USA'), ('createdat', '2020-10-08T09:56:30.7263582')])
This package does not need any additional installation but usage is somewhat more complex.
You can import the package like this.
from xml.etree import ElementTree
To convert the response into the tree you can use.
resp = requests.get('http://restapi.adequateshop.com/api/Traveler?page=6')
tree = ElementTree.fromstring(resp.content)
To access the data then you will have to use indices of the response, which is somewhat like this. tree[4]0.text You will get an output like this.
'Yaamini Yaamini'