создать подэлемент с пространством имен в XML - PullRequest
0 голосов
/ 09 июля 2019

Я хочу создать этот 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>

Ответы [ 2 ]

0 голосов
/ 10 июля 2019

Я решил это с 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')
...
0 голосов
/ 09 июля 2019

Рассмотрите возможность использования выделенного модуля 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"/>
...