【问题标题】:Access a specific tag value in an XML response with ElementTree使用 ElementTree 访问 XML 响应中的特定标记值
【发布时间】:2017-06-09 13:02:10
【问题描述】:

我正在调用一个 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 的值为“空”。我想获取字符串02

有什么帮助吗?

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:
    import xml.etree.ElementTree as ET
    
    tree = ET.XML(response.content)
    tree.findtext(".//{http://wtp}SalidaConsultaSAF/{http://wtp}coderror")
    

    产生'02'

    XPath 是你的朋友。

    【讨论】:

    • 非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2019-06-17
    • 2017-09-18
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多