Xar
Xar

Reputation: 7920

Access a specific tag value in an XML response with ElementTree

I am calling a SOAP web service that returns an XML similar to this:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
    <SalidaConsultaSAF xmlns="http://wtp">
      <coderror>02</coderror>
      <dserror>No records</dserror>
    </SalidaConsultaSAF>
  </soapenv:Body>
</soapenv:Envelope>

I'mm trying to parse it in order to access the value of the tags coderror and dserror, but I'm just failing miserably all the time.

This is just one of the several approaches I've taken:

# parse XML response
from xml.etree import ElementTree as ET

# call the web service
response = requests.post(url, auth=('myUser', 'myPass'),
                         verify=False, data=body, headers=headers)

tree = ET.ElementTree(ET.fromstring(response.content))

a_ = ET.Element(tree) # ==> {'attrib': {}, 'tag': <xml.etree.ElementTree.ElementTree object at 0x7f4736e299d0>, '_children': []}

b_ = ET.SubElement(a_, 'coderror') # ==> {'attrib': {}, 'tag': 'soapenv', '_children': []}

As you can see, the value of variable b is "empty". I would like to obtain the string 02.

Any help, please?

Upvotes: 1

Views: 2180

Answers (1)

Martin Valgur
Martin Valgur

Reputation: 6312

import xml.etree.ElementTree as ET

tree = ET.XML(response.content)
tree.findtext(".//{http://wtp}SalidaConsultaSAF/{http://wtp}coderror")

yields '02'.

XPath is your friend.

Upvotes: 2

Related Questions