2017-01-24 1 views
1

Я звоню веб-службы SOAP, который возвращает XML, похожее на это:Доступ конкретное значение тега в ответ XML с ElementTree

<?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 пытается разобрать его, чтобы получить доступ к стоимости теги coderror и dserror, но я просто терпеть неудачу все время.

Это лишь один из нескольких подходов, которые я взял:

# 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': []} 

Как вы можете видеть, значение переменной b «пустой». Я хотел бы получить строку 02.

Любая помощь, пожалуйста?

ответ

2
import xml.etree.ElementTree as ET 

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

- '02'.

XPath - твой друг.

+0

Большое спасибо! – Xar