【问题标题】:Creating an xml with the help of namespaces using python使用 python 在命名空间的帮助下创建 xml
【发布时间】:2017-03-27 16:58:15
【问题描述】:

我必须创建一个包含命名空间的 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 中的根和元素方法创建一个没有命名空间的 xml 文档,而且我也知道从 xml 文档中解析数据通过使用 xpathlxml 具有命名空间,但我无法理解如何创建像上面这样的文档.我试图找到教程,但在大多数地方都不清楚。有人能帮我理解一下吗?

谢谢

【问题讨论】:

    标签: python xml lxml xml.etree


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2011-03-17
      相关资源
      最近更新 更多