2

I have the following xml string and I want to get the value from ReturnCode in Python. How can I easily do this?

I've tried using element tree:

tree = ET.ElementTree(ET.fromstring(response))
root = tree.getroot()
<API>
    <Result>
        <ErrorCode ErrorType=\"Success\">0</ErrorCode>
        <ReturnCode>0</ReturnCode>
    </Result>
<API>

The actual response value looks like this-

'<API><Result><ErrorCode ErrorType=\"Success\">0</ErrorCode<ReturnCode>0</ReturnCode></Result><API>'

I would like to be able to use the value from ReturnCode for additional logic.

4
  • 1
    I've tried using element tree Show us what you tried. Commented Jun 12, 2019 at 0:41
  • @John Gordon added what I have tried Commented Jun 12, 2019 at 0:44
  • Also state the exact error you get and show the code that produces response, because it's unclear what this variable actually contains. Commented Jun 12, 2019 at 7:35
  • @Tomalak Great point, I guess that would help. I updated original post with that info! Thank you Commented Jun 12, 2019 at 12:58

1 Answer 1

2

As official documents xml.etree.elementtree. Parse your xml document like this:

import xml.etree.ElementTree as ET
# root = ET.fromstring(your_xml_content)
# root.tag
body = '<API><Result><ErrorCode ErrorType="Success">0</ErrorCode><ReturnCode>0</ReturnCode></Result></API>'
response = ET.fromstring(body)
result = response.findall('Result')[0]
return_code = result.find('ReturnCode').text

## output '0'

Updated: I missed result.

Sign up to request clarification or add additional context in comments.

5 Comments

I greatly appreciate the suggestion, however, I receive an error: ValueError: can only parse strings. It appears I am getting back a string. The exact response is: xmlResponse Body: "<API><Result><ErrorCode ErrorType=\"Success\">0</ErrorCode><ReturnCode>0</ReturnCode></Result></API>"
updated last comment with what I think appears to be a string
a = '<API><Result><ErrorCode ErrorType="Success">0</ErrorCode><ReturnCode>0</ReturnCode></Result></API>' then, ET.formstring(a)
to clarify this is Python 3+. not sure if that matters here. I am getting an unresolved error for "find" where you edited the original answer. This is the line with issue return_code = find('ReturnCode').text
return_code = result.find('ReturnCode').text. the missed result, :P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.