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

时间:2017-01-24 16:18:36

标签: python xml elementtree

我正在调用SOAP Web服务,该服务返回类似于此的XML:

<?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的值为&#34;为空&#34;。我想获得字符串02

请帮忙吗?

1 个答案:

答案 0 :(得分:2)

import xml.etree.ElementTree as ET

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

收益'02'

XPath是你的朋友。