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

标签 python xml elementtree

我正在调用返回类似于以下内容的 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>

我试图解析它以访问标签 codeerrordserror 的值,但我总是惨败。

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

# 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

请问有什么帮助吗?

最佳答案

import xml.etree.ElementTree as ET

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

产生'02'

XPath是你的 friend 。

关于python - 使用 ElementTree 访问 XML 响应中的特定标记值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41833122/

相关文章:

python - 如何使用python脚本停止/关闭音频文件(mp3/.wav)

c# - Java XML XPath 解析器到 C#

python - 如何使用python中的elementtree处理xml文件中格式不正确的字符

python - Fillna 如果出现频率最高,则 fillna 为整个列中出现频率最高的值

python - 使用通配符删除redis中的哈希属性

python - 套接字错误 : Address already in use

python - 将元素添加到标题

xml - 返回重复节点集中的 "latest"节点

c# - XML 解析 - 读取简单的 XML 文件并检索值

python - 使用 LXML 编写 XML header