Home > Enterprise >  How to get XML value in Python
How to get XML value in Python

Time:11-14

I'm trying to read XML value from the soap response. Included the response below, I'm trying to read the Bearer token from the below XML. Tried a couple of ways but failed.

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
    <ofo:GetToken xmlns:ofo="http://dummyurl.com/xsd/xyz">
        <ofo:Token>Bearer 123sfafweo123</ofo:Token>
    </ofo:GetToken>
</soapenv:Body>
</soapenv:Envelope>

Code I tried

  import import lxml.etree
 
  # send request to get above response.
  response = requests.post(url, data=body, headers=headers)
  root = lxml.etree.fromstring(response.content)
  textelem = root.find('Envelope/Body/GetToken/Token')
  print(textelem)

CodePudding user response:

Your original code failed to take into account namespaces. There are a couple of way to approach it. This, for example, should work

ns = {"ofo": "http://dummyurl.com/xsd/xyz"}
root.xpath('//ofo:Token/text()',namespaces=ns)[0]

or, if you want to avoid dealing with namespaces:

doc.xpath('//*[local-name()="Token"]/text()')[0]

Output, in either case:

Bearer 123sfafweo123
  • Related