|
1 | 1 | """Wrapper to provide dict-like access to XML via ElementTree.""" |
| 2 | +from __future__ import annotations |
2 | 3 |
|
3 | | -from typing import Mapping |
| 4 | +import xml.etree.ElementTree as ET |
| 5 | +from pathlib import Path |
| 6 | +from typing import Optional, Union |
4 | 7 |
|
| 8 | +import defusedxml.ElementTree as DET |
5 | 9 |
|
6 | | -class XMLProxy(Mapping): |
7 | | - """Class providing dict-like access to edit XML via ElementTree.""" |
| 10 | + |
| 11 | +class XMLProxy: |
| 12 | + """Class providing dict-like access to edit XML via ElementTree. |
| 13 | +
|
| 14 | + Note that this wrapper facade is limited: |
| 15 | + * XML attributes are not supported |
| 16 | + * DTDs are ignored (arbitrary keys can be queried and added) |
| 17 | + * each tag is assumed to either contain a value or more nested tags |
| 18 | + * lists are treated atomically (no way to add/remove element from a collection) |
| 19 | +
|
| 20 | + The semantics is implemented as follows: |
| 21 | + * If there are multiple tags with the same name, a list of XMLProxy nodes is returned |
| 22 | + * If a unique tag does have no nested tags, its `text` string value is returned |
| 23 | + * Otherwise the node is returned |
| 24 | + """ |
| 25 | + |
| 26 | + # NOTE: one could create a separate XMLList wrapper to cover the list case better |
| 27 | + # but need to think through the semantics properly. |
| 28 | + |
| 29 | + def __init__(self, el: ET.Element, *, default_namespace: Optional[str] = None): |
| 30 | + """Wrap an existing XML ElementTree Element.""" |
| 31 | + self._node: ET.Element = el |
| 32 | + self._def_ns = default_namespace |
| 33 | + |
| 34 | + def _qualified_key(self, key: str): |
| 35 | + """If passed key is not qualified, prepends the default namespace (if set).""" |
| 36 | + if key[0] == "{" or not self._def_ns: |
| 37 | + return key |
| 38 | + return "{" + self._def_ns + "}" + key |
| 39 | + |
| 40 | + @classmethod |
| 41 | + def parse(cls, path: Union[str, Path], **kwargs) -> XMLProxy: |
| 42 | + """Parse an XML file into an ElementTree, preserving comments.""" |
| 43 | + path = path if isinstance(path, Path) else Path(path) |
| 44 | + parser = DET.XMLParser(target=ET.TreeBuilder(insert_comments=True)) |
| 45 | + return cls(DET.parse(path, parser=parser).getroot(), **kwargs) |
| 46 | + |
| 47 | + def write(self, path: Union[str, Path], *, header: bool = True, **kwargs): |
| 48 | + """Write the XML DOM to an UTF-8 encoded file.""" |
| 49 | + path = path if isinstance(path, Path) else Path(path) |
| 50 | + et = ET.ElementTree(self._node) |
| 51 | + if self._def_ns and "default_namespace" not in kwargs: |
| 52 | + kwargs["default_namespace"] = self._def_ns |
| 53 | + et.write(path, encoding="UTF-8", xml_declaration=header, **kwargs) |
| 54 | + |
| 55 | + def __repr__(self): |
| 56 | + """See `object.__repr__`.""" |
| 57 | + return str(self._node) |
| 58 | + |
| 59 | + def __len__(self): |
| 60 | + """See `Mapping.__len__`.""" |
| 61 | + return len(self._node) |
| 62 | + |
| 63 | + def __iter__(self): |
| 64 | + """See `Mapping.__iter__`.""" |
| 65 | + return map(XMLProxy, iter(self._node)) |
| 66 | + |
| 67 | + # ---- dict-like access ---- |
| 68 | + |
| 69 | + def get(self, key: str, *, as_node_list: bool = False): |
| 70 | + """See `dict.get`.""" |
| 71 | + if not key: |
| 72 | + raise ValueError("Key must not be an empty string!") |
| 73 | + # if not fully qualified + default NS is given, use it for query |
| 74 | + if lst := self._node.findall(self._qualified_key(key)): |
| 75 | + ns = list(map(lambda x: XMLProxy(x, default_namespace=self._def_ns), lst)) |
| 76 | + if as_node_list: |
| 77 | + return ns # return it as a list an any case if desired |
| 78 | + if len(ns) > 1: |
| 79 | + return ns # node list (multiple matching elements) |
| 80 | + else: |
| 81 | + if ns[0]: # single node (single matched element) |
| 82 | + return ns[0] |
| 83 | + else: # string value (leaf element, i.e. no inner tags) |
| 84 | + return ns[0]._node.text.strip() |
| 85 | + |
| 86 | + def __getitem__(self, key: str): |
| 87 | + """Acts like `dict.__getitem__`, implemented with `get`.""" |
| 88 | + val = self.get(key) |
| 89 | + if val is not None: |
| 90 | + return val |
| 91 | + else: |
| 92 | + raise KeyError(key) |
| 93 | + |
| 94 | + def __contains__(self, key: str) -> bool: |
| 95 | + """Acts like `dict.__contains__`, implemented with `get`.""" |
| 96 | + return self.get(key) is not None |
| 97 | + |
| 98 | + def __delitem__(self, key: str): |
| 99 | + """Acts like `dict.__delitem__`. |
| 100 | +
|
| 101 | + If there are multiple matching tags, **all** of them are removed! |
| 102 | + """ |
| 103 | + nodes = self.get(key, as_node_list=True) |
| 104 | + if not nodes: |
| 105 | + raise KeyError(key) |
| 106 | + for child in nodes: |
| 107 | + self._node.remove(child._node) |
| 108 | + |
| 109 | + def __setitem__(self, key: str, val): |
| 110 | + """See `dict.__setitem__`.""" |
| 111 | + nodes = self.get(key, as_node_list=True) |
| 112 | + if nodes: |
| 113 | + if len(nodes) > 1: |
| 114 | + # delete all (we can't handle lists well) + create new |
| 115 | + del self[key] |
| 116 | + node = ET.SubElement(self._node, self._qualified_key(key)) |
| 117 | + else: |
| 118 | + # take unique node and empty it out (text + inner tags) |
| 119 | + node = nodes[0]._node |
| 120 | + node.text = "" |
| 121 | + for child in iter(node): |
| 122 | + node.remove(child) |
| 123 | + |
| 124 | + # attach value to the tag |
| 125 | + if not isinstance(val, (XMLProxy, list, dict)): # leaf value |
| 126 | + val = val if isinstance(val, str) else str(val) |
| 127 | + node.text = val |
| 128 | + else: # nested dict-like structure |
| 129 | + raise NotImplementedError |
0 commit comments