简体   繁体   中英

Python - How to edit the namespaces of Soap Envelope / xmlns:encodingStyle

I have an issue while creating an XML-file for a SOAP Call

I am using the following code to create the 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)

Thus I get the following XML-file:

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

The first line of the XML-file I need to create has to be like that

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

How do I change the prefix/namespace of URL 2 from xmlns:encodingStyle to soap:encodingStyle or if my approach is wrong how do I add soap:encodingStyle to the envolope?

Thanks in advance

soap:encodingStyle is an attribute bound to a namespace. Add it using the set() method.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM