使用python在名称空间的帮助下创建一个xml

时间:2017-03-27 16:58:15

标签: python xml lxml xml.etree

我必须创建一个包含名称空间的SOAP请求,文档应该如下所示,

<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>

但我知道使用 xml.etree.ElementTree 中的root和element方法创建一个没有命名空间的xml文档,我也知道从xml文档中解析数据其中包含使用 xpath lxml 的命名空间,但我无法理解如何创建上述文档。我试图找到教程,但在大多数地方都很不清楚。有人可以帮我理解这个吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以使用lxml构建器。需要在样板上有点沉重,但嘿是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)

结果:

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>