Bhargav
Bhargav

Reputation: 484

Creating an xml with the help of namespaces using python

I have to create a SOAP request including namespaces, the document should look like below,

<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://bhargavsaidama.com/services/schema/mser/mlistr/v1"
xmlns:v11="http://bhargavsaidama.com/services/schema/gs/rblock/v1"
xmlns:v12="http://bhargavsaidama.com/services/schemas/ut/mi/v1">
<soapenv:Header>
</soapenv:Header>
<soapenv:Body>
<v1:MLreq>
     <v11:IDB>
     </v11:IDB>
</v1:Mlreq>
<v1:Rparams>
        <v12:MsgL>32</v12:MsgL>
</v1:Rparams>
</soapenv:Body>
</soapenv:Envelope>

But I know to create an xml document without namespaces using root and element methods from xml.etree.ElementTree and I was also aware of parsing the data from xml document which has namespaces by using xpath and lxml, but I was unable to understand how to create a document like above. I tried to find tutorials , but in most of the places it is rather unclear. Can some one please help me understand this?

Thanks

Upvotes: 1

Views: 677

Answers (1)

salparadise
salparadise

Reputation: 5825

You can use lxml builder for this. A tad bit heavy on the boilerplate needed, but hey is XML.

from lxml import etree as etree
from lxml.builder import ElementMaker

soap_ns = ElementMaker(namespace='http://schemas.xmlsoap.org/soap/envelope/', nsmap={
    'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
    'v1':'http://bhargavsaidama.com/services/schema/mser/mlistr/v1',
    'v11': 'http://bhargavsaidama.com/services/schema/gs/rblock/v1',
    'v12': 'http://bhargavsaidama.com/services/schemas/ut/mi/v1'
})

v1_ns = ElementMaker(namespace='http://bhargavsaidama.com/services/schema/mser/mlistr/v1')
v11_ns = ElementMaker(namespace='http://bhargavsaidama.com/services/schema/gs/rblock/v1')
v12_ns = ElementMaker(namespace='http://bhargavsaidama.com/services/schemas/ut/mi/v1')

root = soap_ns('Envelope')

body = soap_ns('Body')

mlreq = v1_ns('MLreq', v11_ns('IDB'))

rparams = v1_ns('Rparams', v12_ns('MsgL'))

body.append(mlreq)
body.append(rparams)
root.append(body)

Result:

print etree.tostring(root, pretty_print=True)


<soapenv:Envelope xmlns:v12="http://bhargavsaidama.com/services/schemas/ut/mi/v1" xmlns:v1="http://bhargavsaidama.com/services/schema/mser/mlistr/v1" xmlns:v11="http://bhargavsaidama.com/services/schema/gs/rblock/v1" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <v1:MLreq>
      <v11:IDB/>
    </v1:MLreq>
    <v1:Rparams>
      <v12:MsgL/>
    </v1:Rparams>
  </soapenv:Body>
</soapenv:Envelope>

Upvotes: 1

Related Questions