>我有一个字典,里面有值(字符串,列表,字典),我想将该字典转换为XML格式的字符串。
值包含可能是子字典和列表(不是固定格式)。 所以我想从字典中获取所有值并形成 XML 字符串,而无需使用任何内置函数,例如(导入 xml、元素树等)。
例如:
输入:
{'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>
任何人都可以建议哪种方式很容易做到这一点。
你可以使用这样的东西:
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%sn' % '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%sn' % '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/>