Search code examples
pythonparsingxmltodict

xmltodict with force_list argument returns a list with None element for empty XML list


I'm parsing XML with xmltodict with force_list=('xml_tag') in order to get list for single elements in XML list. And it works! However, in case when xml_tag has no child it returns a [None](list with single None object). How to prevent it?

XML

<Something>
    <Guitar>
        <name>Walden</name>
        <strings>5</strings>
    </Guitar>
    <Pokemons>
    </Pokemons>
</Something>

PYTHON

res = xmltodict.parse(xml, force_list=('Pokemons',))

res = res['Something']['Guitar']['Pokemons']

pprint(res)

>>> [None]

Any suggestions?

[UPDATE]

Sorry, I'm not clarifying what I want. I want to get empty list as result not list with None element


Solution

  • You can pass a postprocessing function to xmltodict, which allows you to modify the dict values.
    But postprocecssing needs to return a key and a value:

    import xmltodict
    import json
    
    
    def postprocessor(path, key, value):
        if key == 'Pokemons' and not value:
            return key, []
        return key, value
    
    xml = """<Something>
        <Guitar>
            <name>Walden</name>
            <strings>5</strings>
        </Guitar>
        <Pokemons>
        </Pokemons>
    </Something>"""
    
    
    res = xmltodict.parse(xml, postprocessor=postprocessor)
    print(json.dumps(res, indent=2, sort_keys=True))
    

    Output:

    {
      "Something": {
        "Guitar": {
          "name": "Walden",
          "strings": "5"
        },
        "Pokemons": []
      }
    }