【问题标题】:Python - How to edit the namespaces of Soap Envelope / xmlns:encodingStylePython - 如何编辑 Soap Envelope / xmlns:encodingStyle 的命名空间
【发布时间】:2021-08-13 15:35:24
【问题描述】:

我在为 SOAP 调用创建 XML 文件时遇到问题

我正在使用以下代码来创建 XML:

from lxml import etree as ET

SOAP_NS = "URL"
ENCODE_NS = "URL2/soap-encoding"
ns_map = {'soap' : SOAP_NS, 'encodingStyle' : ENCODE_NS}

root = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
body = ET.SubElement(root, ET.QName(SOAP_NS, 'Body'), nsmap=ns_map)

Data = ET.SubElement(body, 'Data')
Data.text="1234"
Data.set('type','import')
xml_file = ET.ElementTree(root)
xml_file.write('Test.xml', pretty_print=True)

因此我得到以下 XML 文件:

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

我需要创建的 XML 文件的第一行必须是这样的

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

如何将 URL 2 的前缀/命名空间从 xmlns:encodingStyle 更改为 soap:encodingStyle 或者如果我的方法有误,如何将 soap:encodingStyle 添加到信封?

提前致谢

【问题讨论】:

    标签: python xml soap lxml xml-namespaces


    【解决方案1】:

    soap:encodingStyle 是绑定到命名空间的属性。使用set() 方法添加它。

    from lxml import etree as ET
     
    SOAP_NS = "URL"
    ENCODE_NS = "URL2/soap-encoding"
    ns_map = {'soap' : SOAP_NS}
     
    root = ET.Element(ET.QName(SOAP_NS, 'Envelope'), nsmap=ns_map)
    root.set(ET.QName(SOAP_NS, "encodingStyle"), ENCODE_NS)
     
    body = ET.SubElement(root, ET.QName(SOAP_NS, 'Body'), nsmap=ns_map)
     
    Data = ET.SubElement(body, 'Data')
    Data.text="1234"
    Data.set('type','import')
    xml_file = ET.ElementTree(root)
    xml_file.write('Test.xml', pretty_print=True)
    

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 2017-12-05
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多