【问题标题】:create subelement with namespace in xml在 xml 中创建具有命名空间的子元素
【发布时间】:2019-07-09 14:12:15
【问题描述】:

我想创建这个xml,但我不知道如何使用命名空间创建子元素IsAddSegments

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <ISAddSegments xmlns="http://www.blue-order.com/ma/integrationservicews/api">
            <accessKey>key</accessKey>
            <objectID>
                <guid>guid</guid>
            </objectID>
            <StratumName>STRATUM</StratumName>
            <Segments>
                <Segment>
                    <Begin>00:00:00:00</Begin>
                    <Content>TEXT</Content>
                    <End>00:00:10:00</End>
                </Segment>
            </Segments>
        </ISAddSegments>
    </soapenv:Body>
</soapenv:Envelope>

这就是我所拥有的:

import xml.etree.ElementTree as ET

Envelope = ET.Element("{http://www.w3.org/2003/05/soap-envelope}Envelope")
Body = ET.SubElement(Envelope, '{http://www.w3.org/2003/05/soap-envelope}Body')
ET.register_namespace('soapenv', 'http://www.w3.org/2003/05/soap-envelope')
ISAddSegments = ET.SubElement(Body, '{http://www.blue-order.com/ma/integrationservicews/api}ISAddSegments')
...

但这会在主元素中创建一个额外的命名空间,这不是我需要的。

<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:ns1="http://www.blue-order.com/ma/integrationservicews/api" xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <ns1:ISAddSegments>

【问题讨论】:

  • 命名空间定义应该在 xml 文档的顶部,以便根据 lxml 生成正确的 XML。

标签: python xml soap namespaces


【解决方案1】:

我用lxml解决了这个问题:

from lxml import etree as etree

ns1 = 'http://www.w3.org/2003/05/soap-envelope'
ns2 = 'http://www.blue-order.com/ma/integrationservicews/api'

Envelope = etree.Element('{ns1}Envelope', nsmap = {'soapenv': ns1})
Body = etree.SubElement(Envelope, '{ns1}Body')
ISAddSegments = etree.SubElement(Body, 'ISAddSegments', nsmap = {None : ns2})
accessKey = etree.SubElement(ISAddSegments, 'accessKey')
...

【讨论】:

    【解决方案2】:

    考虑使用专用的 SOAP 模块,例如 suds。然后,您可以通过将ns 提供给Element 来创建自定义命名空间。该值应该是一个包含命名空间名称和定义它的 url 的元组:

    from suds.sax.element import Element
    
    custom_namespace = ('custom_namespace', 'http://url/namespace.xsd')
    element_with_custom_namespace = Element('Element', ns=custom_namespace)
    
    print(element_with_custom_namespace)
    # <custom_namespace:Element xmlns:custom_namespace="http://url/namespace.xsd"/>
    

    【讨论】:

    • 如何生成其余的 xml?我没有找到很多关于suds的信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多