gpt4 book ai didi

python - 将 dict 转换为具有不同命名空间的 xml

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:29 25 4
gpt4 key购买 nike

我有这样的字典:

dict1 = {"properties xmlns=http://openconfig.net/yang/interfaces/ip": {"property": [{"name": "admin-state", "config xmlns=http://openconfig.net/yang/interfaces/ip": {"name": "admin-state", "value xmlns=http://openconfig.net/yang/interfaces/ip": "DISABLED"}}]}}
args = collections.OrderedDict(dict1)

我正在尝试将其转换为 xml,保持命名空间完整。

我尝试将字典转换为有序字典,然后使用 dict2xml 将其转换为 xml

dict1 = {"properties xmlns=http://openconfig.net/yang/interfaces/ip": {"property": [{"name": "admin-state", "config xmlns=http://openconfig.net/yang/interfaces/ip": {"name": "admin-state", "value xmlns=http://openconfig.net/yang/interfaces/ip": "DISABLED"}}]}}
args = collections.OrderedDict(dict1)
args = collections.OrderedDict(dict1)
dictXml = str(dict2xml(args,indent='')).replace('\n','')

输出是:

'<properties_xmlns_http:__openconfig.net_yang_interfaces_ip><property><config_xmlns_http:__openconfig.net_yang_interfaces_ip><name>admin-state</name><value_xmlns_http:__openconfig.net_yang_interfaces_ip>DISABLED</value_xmlns_http:__openconfig.net_yang_interfaces_ip></config_xmlns_http:__openconfig.net_yang_interfaces_ip><name>admin-state</name></property></properties_xmlns_http:__openconfig.net_yang_interfaces_ip>'

预期输出是:

<properties xmlns=http://openconfig.net/yang/interfaces/ip><property><config xmlns=http://openconfig.net/yang/interfaces/ip><name>admin-state</name><value xmlns=http://openconfig.net/yang/interfaces/ip>DISABLED</value></config><name>admin-state</name></property></properties>

最佳答案

您可以尝试使用这个:https://github.com/watzon/xmler它是支持命名空间的替代方案:

import dict2xml from xmler

myDict = {
"RootTag": { # The root tag. Will not necessarily be root. (see #customRoot)
"@ns": "soapenv", # The namespace for the RootTag. The RootTag will appear as <soapenv:RootTag ...>
"@attrs": { # @attrs takes a dictionary. each key-value pair will become an attribute
{ "xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/" }
},
"childTag": {
"@attrs": {
"someAttribute": "colors are nice"
},
"grandchild": "This is a text tag"
}
}
}

print(dict2xml(myDict, pretty=True, customRoot=None)

返回

<soapenv:RootTag xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<childTag someAttribute="colors are nice">
<grandchild>This is a text tag</grandchild>
</childTag>
</soapenv:RootTag>

(来自 github)

关于python - 将 dict 转换为具有不同命名空间的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57258231/

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