Skip to content

Commit

Permalink
Added the force_list argument to force a level of the hierarchy to al…
Browse files Browse the repository at this point in the history
…ways be a list. This makes it easier to write code that handles a level of the hierarchy where there may be 1 or more entries.
  • Loading branch information
Jonathan Looney authored and guewen committed Nov 16, 2015
1 parent 579a005 commit cd067cb
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions xmltodict.py
Expand Up @@ -50,7 +50,8 @@ def __init__(self,
dict_constructor=OrderedDict,
strip_whitespace=True,
namespace_separator=':',
namespaces=None):
namespaces=None,
force_list=()):
self.path = []
self.stack = []
self.data = None
Expand All @@ -67,6 +68,7 @@ def __init__(self,
self.strip_whitespace = strip_whitespace
self.namespace_separator = namespace_separator
self.namespaces = namespaces
self.force_list = force_list

def _build_name(self, full_name):
if not self.namespaces:
Expand Down Expand Up @@ -148,7 +150,10 @@ def push_data(self, item, key, data):
else:
item[key] = [value, data]
except KeyError:
item[key] = data
if key in self.force_list:
item[key] = [data]
else:
item[key] = data
return item


Expand Down Expand Up @@ -220,6 +225,37 @@ def parse(xml_input, encoding=None, expat=expat, process_namespaces=False,
>>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat)
OrderedDict([(u'a', u'hello')])
You can use the force_list argument to force lists to be created even
when there is only a single child of a given level of hierarchy. The
force_list argument is a tuple of keys. If the key for a given level
of hierarchy is in the force_list argument, that level of hierarchy
will have a list as a child (even if there is only one sub-element).
The index_keys operation takes precendence over this. This is applied
after any user-supplied postprocessor has already run.
For example, given this input:
<servers>
<server>
<name>host1</name>
<os>Linux</os>
<interfaces>
<interface>
<name>em0</name>
<ip_address>10.0.0.1</ip_address>
</interface>
</interfaces>
</server>
</servers>
If called with force_list=('interface',), it will produce
this dictionary:
{'servers':
{'server':
{'name': 'host1',
'os': 'Linux'},
'interfaces':
{'interface':
[ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } }
"""
handler = _DictSAXHandler(namespace_separator=namespace_separator,
**kwargs)
Expand Down

0 comments on commit cd067cb

Please sign in to comment.