import xmltodict
test_data = {'value1': 1, 'parent_lvl1': {'parent_Lvl2': {'value1': 2, 'value2': 3}}}
print("test_data : ", test_data)
xml_str = xmltodict.unparse({'settings' : test_data})
print("dict to xml string :", xml_str)
test_data_re = xmltodict.parse(xml_str, dict_constructor=dict)
print("xml_str back to dict : ", test_data_re['settings'])
结果是: test_data : {'parent_lvl1': {'parent_Lvl2': {'value2': 3, 'value1': 2}}, 'value1': 1} 字典到 xml 字符串: 321 xml_str 返回 dict : {'parent_lvl1': {'parent_Lvl2': {'value2': '3', 'value1': '2'}}, 'value1': '1'}
结果是,当我对旧词典和新词典进行比较时,它们是不同的。如何让 xmltodict 解析它首先解析的内容
最佳答案
我认为您不应该期望它们总体上和始终相同。
在解析过程中,整数值不会自动转换为整数,并且所有内容都会解析为字符串,但您有几种方法可以控制类型转换。例如,您可以指定一个后处理器并尝试将以 value
开头的键的值转换为整数:
def postprocessor(path, key, value):
if key.startswith("value"):
try:
return key, int(value)
except (ValueError, TypeError):
return key, value
return key, value
test_data_re = xmltodict.parse(xml_str, dict_constructor=dict, postprocessor=postprocessor)
print("xml_str back to dict : ", test_data_re['settings'])
这会产生:
xml_str back to dict : {'value1': 1, 'parent_lvl1': {'parent_Lvl2': {'value1': 2, 'value2': 3}}}
顺便说一句,寻找 xmltodict
示例用法的好地方是 xmltodict
tests ,检查一下。
关于python - xmltodict unparse 解析不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744074/