使用 ElementTree 访问 XML 响应中的特定标签值

Access a specific tag value in an XML response with ElementTree

我正在调用 returns 一个 XML 类似于此的 SOAP Web 服务:

<?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>

我正在尝试解析它以访问标签 coderrordserror 的值,但我一直都在悲惨地失败。

这只是我采用的几种方法之一:

# 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的值为"empty"。我想获取字符串 02.

有什么帮助吗?

import xml.etree.ElementTree as ET

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

产量 '02'.

XPath是你的朋友。