| 1 |
"""Utilities for converting between dictionaries and XML.""" |
| 2 |
|
| 3 |
import contextlib |
| 4 |
|
| 5 |
with contextlib.suppress(ImportError): |
| 6 |
from defusedxml import ElementTree |
| 7 |
|
| 8 |
|
| 9 |
def dict2xml(d, elementname="element", pretty=True, allow_attributes=True, level=0): |
| 10 |
"""Convert a dictionary to an XML string.""" |
| 11 |
indent = (pretty and "\t" * level) or "" |
| 12 |
xml = [] |
| 13 |
attributes = [] |
| 14 |
children = [] |
| 15 |
|
| 16 |
if isinstance(d, (dict, list)): |
| 17 |
start_tag = [] |
| 18 |
start_tag.append(f"{indent}<{elementname}") |
| 19 |
|
| 20 |
if isinstance(d, dict): |
| 21 |
for key in d: |
| 22 |
value = d[key] |
| 23 |
if isinstance(value, (dict, list)) or not allow_attributes: |
| 24 |
children.append( |
| 25 |
dict2xml(value, key, pretty, allow_attributes, level + 1) |
| 26 |
) |
| 27 |
else: |
| 28 |
if pretty: |
| 29 |
attributes.append(f"\n{indent}") |
| 30 |
attributes.append(f' {key}="{escape(str(value))}"') |
| 31 |
else: |
| 32 |
children.extend( |
| 33 |
dict2xml(value, "item", pretty, allow_attributes, level + 1) |
| 34 |
for value in d |
| 35 |
) |
| 36 |
|
| 37 |
start_tag.extend(attributes) |
| 38 |
start_tag.append((children and ">") or "/>") |
| 39 |
xml.append("".join(start_tag)) |
| 40 |
|
| 41 |
if children: |
| 42 |
xml += children |
| 43 |
xml.append(f"{indent}</{elementname}>") |
| 44 |
else: |
| 45 |
xml.append(f"{indent}<{elementname}>{escape(str(d))}</{elementname}>") |
| 46 |
|
| 47 |
return ((pretty and "\n") or "").join(xml) |
| 48 |
|
| 49 |
|
| 50 |
def escape(xml): |
| 51 |
"""Escape XML special characters in a string.""" |
| 52 |
return ( |
| 53 |
xml.replace("&", "&") |
| 54 |
.replace("<", "<") |
| 55 |
.replace(">", ">") |
| 56 |
.replace('"', """) |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
class ETreeDict(dict): |
| 61 |
"""A class to parse XML data into a dictionary-like structure.""" |
| 62 |
|
| 63 |
# Roughly follow "Converting Between XML and JSON" |
| 64 |
# https://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html |
| 65 |
|
| 66 |
def __init__(self, etree): |
| 67 |
super().__init__() |
| 68 |
children = len(etree) |
| 69 |
if etree.attrib or etree.text or children: |
| 70 |
self[etree.tag] = {f"@{k}": v for k, v in etree.attrib.items()} |
| 71 |
if etree.text: |
| 72 |
text = etree.text.strip() |
| 73 |
if etree.attrib or children: |
| 74 |
if text: |
| 75 |
self[etree.tag]["#text"] = text |
| 76 |
else: |
| 77 |
self[etree.tag] = text |
| 78 |
if children: |
| 79 |
d = self[etree.tag] |
| 80 |
for child in etree: |
| 81 |
for k, v in ETreeDict(child).items(): |
| 82 |
if k in d: |
| 83 |
if not isinstance(d[k], list): |
| 84 |
d[k] = [d[k]] |
| 85 |
d[k].append(v) |
| 86 |
else: |
| 87 |
d[k] = v |
| 88 |
else: |
| 89 |
self[etree.tag] = None |
| 90 |
|
| 91 |
def __repr__(self): |
| 92 |
"""Return a string representation of the ETreeDict. |
| 93 |
|
| 94 |
od.__repr__() <==> repr(od). |
| 95 |
|
| 96 |
Returns: |
| 97 |
str: A string representation of the ETreeDict. |
| 98 |
""" |
| 99 |
l = [] |
| 100 |
for k in self: |
| 101 |
v = self[k] |
| 102 |
l.append(f"{k!r}: {v!r}") |
| 103 |
return "{{{}}}".format(", ".join(l)) |
| 104 |
|
| 105 |
@property |
| 106 |
def json(self): |
| 107 |
"""Return a JSON representation of the ETreeDict. |
| 108 |
|
| 109 |
Returns: |
| 110 |
str: A JSON string representation of the ETreeDict. |
| 111 |
""" |
| 112 |
import json |
| 113 |
|
| 114 |
return json.dumps(self) |
| 115 |
|
| 116 |
|
| 117 |
class XMLDict(ETreeDict): |
| 118 |
"""A class to parse XML data into a dictionary-like structure.""" |
| 119 |
|
| 120 |
def __init__(self, xml): |
| 121 |
etree = ElementTree.fromstring(xml) |
| 122 |
ETreeDict.__init__(self, etree) |