1

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)
3
  • 1
    Show what you tried and how they failed. Commented Nov 13, 2022 at 1:24
  • @user29496 Please edit your question and add this attempt there, not in a comment. Commented Nov 13, 2022 at 14:52
  • included the code I tried Commented Nov 13, 2022 at 17:14

1 Answer 1

1

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

2 Comments

Thanks a lot. I was able to retrieve the code
@user29496 Glad it worked for you!

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.