简体   繁体   English

xmltodict unparse解析不一样

[英]xmltodict unparse parse not the same

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'])

Results are : test_data : {'parent_lvl1': {'parent_Lvl2': {'value2': 3, 'value1': 2}}, 'value1': 1} dict to xml string : 321 xml_str back to dict : {'parent_lvl1': {'parent_Lvl2': {'value2': '3', 'value1': '2'}}, 'value1': '1'} 结果是:test_data:{'parent_lvl1':{'parent_Lvl2':{'value2':3,'value1':2}},'value1':1}字典到xml字符串:321 xml_str返回到字典:{'parent_lvl1 ':{'parent_Lvl2':{'value2':'3','value1':'2'}},'value1':'1'}

The result is that when I do a comparison between the old dict and the new they are different. 结果是,当我在旧字典和新字典之间进行比较时,它们是不同的。 How do I get xmltodict to unparse what it parsed in the first place 我如何获取xmltodict首先解析它解析的内容

I don't think you should expect both of them be the same in general and all the time. 我认为您不应该期望它们在总体上和所有时间都相同。

The integer values are not being cast to integers during parsing automatically and everything is parsed into strings, but you have a few ways to control the type conversion. 在自动解析过程中不会将整数值转换为整数,并且所有内容都将解析为字符串,但是您可以通过几种方法来控制类型转换。 For example, you could specify a post processor and try converting values to integers for keys starting with value : 例如,您可以指定一个后处理器,然后尝试将以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'])

This would produce: 这将产生:

xml_str back to dict :  {'value1': 1, 'parent_lvl1': {'parent_Lvl2': {'value1': 2, 'value2': 3}}}

Btw, a good place to look for xmltodict sample usages is xmltodict tests , check it out. 顺便说一句,查找xmltodict示例用法的好地方是xmltodict tests ,将其检出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM