Skip to content

Instantly share code, notes, and snippets.

@jsenin
Created May 18, 2017 11:40
Show Gist options
  • Save jsenin/d0a980a76cbdfa0f6e08f75d74173885 to your computer and use it in GitHub Desktop.
Save jsenin/d0a980a76cbdfa0f6e08f75d74173885 to your computer and use it in GitHub Desktop.
soap xml with namespaces using lxml and python
from lxml import etree
from lxml.builder import ElementMaker
class NewRpcMessageEncoder(object):
def _envelope(self, request_id, hold_requests):
SOAP_ENV = "http://schemas.xmlsoap.org/soap/envelope/"
SOAP_ENC = "http://schemas.xmlsoap.org/soap/encoding/"
XSD = "http://www.w3.org/2001/XMLSchema"
XSI = "http://www.w3.org/2001/XMLSchema-instance"
CWMP = "urn:dslforum-org:cwmp-1-2"
soap_enc = ElementMaker(namespace=SOAP_ENC)
xsd = ElementMaker(namespace=XSD)
xsi = ElementMaker(namespace=XSI)
cwmp = ElementMaker(namespace=CWMP)
soap = ElementMaker(namespace=SOAP_ENV,
nsmap={
'xsi' : XSI,
'soap' : SOAP_ENV,
'soap-enc' : SOAP_ENC,
'xsd' : XSD,
'cwmp' : CWMP})
SOAP_MUST_UNDERSTAND = '{{{0}}}mustUnderstand'.format(SOAP_ENV)
MUST_UNDERSTAND = '1'
body=()
xml = soap.Envelope(
soap.Header(
cwmp.ID(str(request_id), {SOAP_MUST_UNDERSTAND : MUST_UNDERSTAND}),
cwmp.HoldRequests('0', {SOAP_MUST_UNDERSTAND : MUST_UNDERSTAND})
),
soap.Body(body)
)
def __str__(self):
xml_declaration = """<?xml version="1.0" encoding="utf-8"?>\n"""
# xml_declaration add's back slash to version an encoding quotes
return xml_declaration + etree.tostring(xml, encoding='utf-8' , xml_declaration=False, pretty_print=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment