我有一个带有值的字典(字符串,列表,字典)我想将该字典转换为xml格式字符串。
值包含可能是子词典和列表(不是固定格式)。所以我想从dict获取所有值并形成xml字符串,而不使用任何内置函数,如(import xml,ElementTree等)。
例如:
输入:
{'Employee':{ 'Id' : 'TA23434', 'Name':'Kesavan' , 'Email':'k7@gmail.com' , 'Roles':[ {'Name':'Admin' ,'RoleId':'xa1234' },{'Name':'Engineer' , 'RoleId':'xa5678' }], 'Test':{'a':'A','b':'b'} }}
输出应为:
<Employee>
<Id>TA23434</Id>
<Name>Kesaven</Name>
<Email>, ..... </Email>
<Roles>
<Roles-1>
<Name>Admin</Name>
<RoleId>xa1234</RoleId>
</Roles-1>
<Roles-2>
<Name>Admin</Name>
<RoleId>xa1234</RoleId>
</Roles-2>
<Roles>
<Test>
<a>A</a>
<b>B</b>
</Test>
</Employee>
任何人都可以建议这样做很容易。
答案 0 :(得分:1)
您可以使用以下内容:
def to_tag(k, v):
"""Create a new tag for the given key k and value v"""
return '<{key}>{value}<{key}/>'.format(key=k, value=get_content(k, v))
def get_content(k, v):
"""Create the content of a tag by deciding what to do depending on the content of the value"""
if isinstance(v, str):
# it's a string, so just return the value
return v
elif isinstance(v, dict):
# it's a dict, so create a new tag for each element
# and join them with newlines
return '\n%s\n' % '\n'.join(to_tag(*e) for e in v.items())
elif isinstance(v, list):
# it's a list, so create a new key for each element
# by using the enumerate method and create new tags
return '\n%s\n' % '\n'.join(to_tag('{key}-{value}'.format(key=k, value=i+1), e) for i, e in enumerate(v))
d = {'Employee':{ 'Id' : 'TA23434', 'Name':'Kesavan' , 'Email':'k7@gmail.com' , 'Roles':[ {'Name':'Admin' ,'RoleId':'xa1234' },{'Name':'Engineer' , 'RoleId':'xa5678' }], 'Test':{'a':'A','b':'b'} }}
for k,v in d.items():
print to_tag(k, v)
我添加了一些评论,但应该清楚发生了什么,这应该足以让你开始。
dict
未在python中排序,因此生成的XML也没有排序。
<强>结果:强>
<Employee>
<Email>k7@gmail.com<Email/>
<Test>
<a>A<a/>
<b>b<b/>
<Test/>
<Id>TA23434<Id/>
<Roles>
<Roles-1>
<RoleId>xa1234<RoleId/>
<Name>Admin<Name/>
<Roles-1/>
<Roles-2>
<RoleId>xa5678<RoleId/>
<Name>Engineer<Name/>
<Roles-2/>
<Roles/>
<Name>Kesavan<Name/>
<Employee/>