| 1 |
def clean_node_dict(node, template=None): |
| 2 |
"""Clean a UBL-style node dictionary by removing child nodes not defined in the template. |
| 3 |
Attributes and metadata (like '_text', 'CurrencyID', 'SchemeID') are preserved. |
| 4 |
|
| 5 |
:param node: dict representing the node |
| 6 |
:param template: dict defining allowed child keys |
| 7 |
:return: cleaned node dict |
| 8 |
""" |
| 9 |
if not isinstance(node, dict) or template is None: |
| 10 |
return node |
| 11 |
|
| 12 |
for child_tag, child in list(node.items()): |
| 13 |
|
| 14 |
if child_tag.startswith('_') or not isinstance(child, (dict, list)): |
| 15 |
continue |
| 16 |
|
| 17 |
|
| 18 |
if child_tag not in template: |
| 19 |
node.pop(child_tag) |
| 20 |
continue |
| 21 |
|
| 22 |
child_template = template.get(child_tag) |
| 23 |
|
| 24 |
if isinstance(child, dict): |
| 25 |
|
| 26 |
cleaned_child = clean_node_dict(child, template=child_template) |
| 27 |
node[child_tag] = cleaned_child |
| 28 |
|
| 29 |
elif isinstance(child, list): |
| 30 |
cleaned_list = [] |
| 31 |
for item in child: |
| 32 |
if isinstance(item, dict): |
| 33 |
cleaned_item = clean_node_dict(item, template=child_template) |
| 34 |
cleaned_list.append(cleaned_item) |
| 35 |
else: |
| 36 |
|
| 37 |
cleaned_list.append(item) |
| 38 |
node[child_tag] = cleaned_list |
| 39 |
|
| 40 |
return node |