如何用Python从XML中提取内嵌的SOAP信封并输出?
提取XML中ShipmentCreation节点下的SOAP信封(Python实现)
由于你的XML包含命名空间,直接查找元素会失败,需要先处理命名空间映射,下面提供两种可行方案:
方案一:使用Python标准库xml.etree.ElementTree
无需额外安装依赖,适合快速实现:
import xml.etree.ElementTree as ET # 读取XML文件(如果是字符串输入,替换为root = ET.fromstring(xml_content)) tree = ET.parse("input.xml") root = tree.getroot() # 定义XML中的命名空间映射 ns_map = { "oagis": "http://schema.infor.com/InforOAGIS/2", "soapenv": "http://schemas.xmlsoap.org/soap/envelope/" } # 定位到ShipmentCreation节点下的soapenv:Envelope元素 soap_envelope = root.find(".//oagis:ShipmentCreation/soapenv:Envelope", ns_map) # 将元素转换为完整的XML字符串 result = ET.tostring(soap_envelope, encoding="unicode") # 输出或赋值给变量使用 print(result)
方案二:使用lxml库(推荐,支持格式保留)
如果需要保留原XML的缩进格式,lxml的处理更友好,先通过pip安装:
pip install lxml
然后执行代码:
from lxml import etree # 读取XML文件 tree = etree.parse("input.xml") root = tree.getroot() # 命名空间映射 ns_map = { "oagis": "http://schema.infor.com/InforOAGIS/2", "soapenv": "http://schemas.xmlsoap.org/soap/envelope/" } # 通过XPath定位目标元素 soap_envelope = root.xpath(".//oagis:ShipmentCreation/soapenv:Envelope", namespaces=ns_map)[0] # 转换为带缩进的XML字符串 result = etree.tostring(soap_envelope, encoding="unicode", pretty_print=True) print(result)
关键说明
- 必须正确定义命名空间映射,XML中的元素都绑定了对应的命名空间,不指定的话无法匹配到目标节点;
- 两种方案最终都会得到包含完整
<soapenv:Envelope>标签及内部内容的字符串,直接赋值给变量即可使用。
内容的提问来源于stack exchange,提问作者lavanya t
相关产品推荐
相关产品推荐

