diff --git a/README.markdown b/README.markdown index 973a656..6bb9344 100644 --- a/README.markdown +++ b/README.markdown @@ -240,6 +240,41 @@ Starting in version 1.7.1, you can wrap values in CDATA by setting the optional If you do not set `cdata` to `True`, the default value is `False` and values are not wrapped. +Adding Custom Attributes +======================== + +You can add custom attributes to nodes by adding a child `dict` named `@attrs` to a parent `dict` like so: + +```python3 +my_dict = { + "Family": { + "@attrs": { + "Tree": "Menelaws" + }, + "Name": "Lewis Menelaws", + "Occupation": "Programmer", + "Programming Language": "Python" + } +} +``` +The key will be the name of the custom attribute while the value will be the value of that custom attribute. + +Running a standard `dicttoxml` you will get a result like this: + +```xml + + + + Lewis Menelaws + Programmer + Python + + +``` + + + + Debugging ========= diff --git a/dicttoxml.py b/dicttoxml.py index ae1384a..29b185b 100755 --- a/dicttoxml.py +++ b/dicttoxml.py @@ -208,9 +208,7 @@ def convert_dict(obj, ids, parent, attr_type, item_func, cdata): LOG.info('Looping inside convert_dict(): key="%s", val="%s", type(val)="%s"' % ( unicode_me(key), unicode_me(val), type(val).__name__) ) - attr = {} if not ids else {'id': '%s' % (get_unique_id(parent)) } - key, attr = make_valid_xml_name(key, attr) if isinstance(val, numbers.Number) or type(val) in (str, unicode): @@ -225,12 +223,25 @@ def convert_dict(obj, ids, parent, attr_type, item_func, cdata): elif isinstance(val, dict): if attr_type: attr['type'] = get_xml_type(val) - addline('<%s%s>%s' % ( - key, make_attrstring(attr), - convert_dict(val, ids, key, attr_type, item_func, cdata), - key + + if list(val.keys())[0] == '@attrs': + # If first item is @attrs + + custom_attrs = val['@attrs'] + val.pop('@attrs', None) + addline('<%s%s>%s' % ( + key, make_attrstring(custom_attrs), + convert_dict(val, ids, key, attr_type, item_func, cdata), + key + ) + ) + else: + addline('<%s%s>%s' % ( + key, make_attrstring(attr), + convert_dict(val, ids, key, attr_type, item_func, cdata), + key + ) ) - ) elif isinstance(val, collections.Iterable): if attr_type: