【问题标题】:xmltodict unparse parse not the samexmltodict unparse 解析不一样
【发布时间】:2018-12-12 13:25:38
【问题描述】:
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 解析它首先解析的内容

【问题讨论】:

    标签: python xmltodict


    【解决方案1】:

    我认为您不应该期望它们在总体上和所有时间都相同。

    在解析过程中,整数值不会自动转换为整数,所有内容都被解析为字符串,但是您有几种方法可以控制类型转换。例如,您可以指定一个后处理器并尝试将值转换为以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,看看吧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多