使用Python LXML库解析SOAP响应中的customer_id字段
问题原因
etree.fromstring()方法直接返回XML的根节点_Element对象,不需要调用getroot()方法,只有etree.parse()返回的ElementTree对象才支持getroot(),这是报错的直接原因。- 目标SOAP响应带了自定义命名空间,使用XPath查询时必须显式指定命名空间映射,不能直接用标签名查询。
实现代码
from lxml import etree # 直接解析响应内容,返回值就是根节点,无需调用getroot() root = etree.fromstring(response.content) # 定义和XML对应命名空间映射 ns = { 'soap11env': 'http://schemas.xmlsoap.org/soap/envelope/', 'tns': 'me.web.3.5.4.0', 's1': 'myservice.mymodels.models' } # 方式1:按完整路径查询,稳定性更高 customer_id = root.xpath('./soap11env:Body/tns:orderResponse/tns:orderResult/s1:customer_id/text()', namespaces=ns)[0] # 方式2:直接全局查询对应节点,写法更简洁 # customer_id = root.xpath('//s1:customer_id/text()', namespaces=ns)[0] print(customer_id) # 输出结果:12345
内容的提问来源于stack exchange,提问作者Night Rider
相关产品推荐
相关产品推荐

