gpt4 book ai didi

python - 在xml中创建具有命名空间的子元素

转载 作者:行者123 更新时间:2023-12-04 16:55:40 24 4
gpt4 key购买 nike

我想创建这个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>

最佳答案

我用 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')
...

关于python - 在xml中创建具有命名空间的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56954545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com