在互联网上的示例中绘制了一个小函数,但是递归存在问题......
def toSimpleXml(data, wrap = False):
result = list()
input_data_type = type(data)
if input_data_type is list:
for sub_element in data:
result.append(toSimpleXml(sub_element))
return ''.join(result)
elif input_data_type is dict:
for tag_name in data:
sub_element = data[tag_name]
result.append('<%s>' % tag_name)
result.append(toSimpleXml(sub_element))
result.append('</%s>' % tag_name)
return ''.join(result)
if wrap:
return '<%s>%s</%s>' % (wrap, data, wrap)
return data
data = [{'element_1': 'value_1'}, {'element_2': {'element_2_1': 'value_2_1'}}, {'element_1': 'value_1'}]
print toSimpleXml(data, 'root')
根据想法结果应该包含root
,但wrap
变量为false ...
答案 0 :(得分:3)
该函数返回太早,wrap
即可发挥作用。设置data
而不是返回:
def toSimpleXml(data, wrap = False):
result = list()
input_data_type = type(data)
if input_data_type is list:
for sub_element in data:
result.append(toSimpleXml(sub_element))
data = ''.join(result)
elif input_data_type is dict:
for tag_name in data:
sub_element = data[tag_name]
result.append('<%s>' % tag_name)
result.append(toSimpleXml(sub_element))
result.append('</%s>' % tag_name)
data = ''.join(result)
if wrap:
return '<%s>%s</%s>' % (wrap, data, wrap)
return data
现在实际上已达到if wrap
语句:
>>> print toSimpleXml(data, 'root')
<root><element_1>value_1</element_1><element_2><element_2_1>value_2_1</element_2_1></element_2><element_1>value_1</element_1></root>