You need to enable JavaScript to run this app. Python使用lxml生成SOAP报文时如何添加soap:encodingStyle属性
优惠活动
大模型
产品
解决方案
定价
更多

Python使用lxml生成SOAP报文时如何添加soap:encodingStyle属性

问题核心

你当前的写法把encodingStyle放到了命名空间映射表nsmap中,所以lxml会将其生成为xmlns:开头的命名空间声明,而你需要的是<soap:Envelope>节点下的一个带soap前缀的属性,不是新增命名空间。


修改方案

  1. 调整nsmap,仅保留soap命名空间的前缀映射即可
  2. 构造Envelope节点后,手动为其添加带soap命名空间的encodingStyle属性

修改后的完整代码如下:

from lxml import etree as ET

SOAP_NS = "URL1"
ENCODE_NS = "URL2/soap-encoding"
# 仅保留soap的命名空间映射
ns_map = {'soap' : SOAP_NS}

root = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
# 给Envelope添加soap:encodingStyle属性,属性名用QName绑定soap命名空间
root.set(ET.QName(SOAP_NS, 'encodingStyle'), ENCODE_NS)

body = ET.SubElement(root, ET.QName(SOAP_NS, 'Body'))
Data = ET.SubElement(body, 'Data')
Data.text="1234"
Data.set('type','import')

xml_file = ET.ElementTree(root)
# 若需要XML首行声明,可添加参数xml_declaration=True
xml_file.write('Test.xml', pretty_print=True, encoding='utf-8')

输出验证

运行上述代码生成的XML结构完全符合要求:

<soap:Envelope xmlns:soap="URL1" soap:encodingStyle="URL2/soap-encoding">
  <soap:Body>
    <Data type="import">1234</Data>
  </soap:Body>
</soap:Envelope>

内容的提问来源于stack exchange,提问作者Det-X

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 22:15:04