Repository navigation
Expand file tree
/
Copy pathxml.py
More file actions
148 lines (116 loc) · 4.45 KB
/
Copy pathxml.py
File metadata and controls
148 lines (116 loc) · 4.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
<
8000
div data-line-number="13" class="react-line-number react-code-text" style="padding-right:16px">1314
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
# [2014] - [2025] MinIO, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""XML encoding and decoding functions."""
from __future__ import annotations
import io
from typing import Optional, TypeVar
from xml.etree import ElementTree as ET
from typing_extensions import Protocol
_S3_NAMESPACE = "http://s3.amazonaws.com/doc/2006-03-01/"
def Element( # pylint: disable=invalid-name
tag: str,
namespace: str = _S3_NAMESPACE,
) -> ET.Element:
"""Create ElementTree.Element with tag and namespace."""
return ET.Element(tag, {"xmlns": namespace} if namespace else {})
def SubElement( # pylint: disable=invalid-name
parent: ET.Element, tag: str, text: Optional[str] = None
) -> ET.Element:
"""Create ElementTree.SubElement on parent with tag and text."""
element = ET.SubElement(parent, tag)
if text is not None:
element.text = text
return element
def _namespaced(element: ET.Element, name: str) -> tuple[str, dict[str, str]]:
"""Namespace arguments for find and findall."""
def _get_namespace() -> str:
"""Exact namespace if found."""
start = element.tag.find("{")
if start < 0:
return ""
start += 1
end = element.tag.find("}")
if end < 0:
return ""
return element.tag[start:end]
namespace = _get_namespace()
if namespace:
name = "/".join(f"ns:{token}" for token in name.split("/"))
return name, {"ns": namespace}
return name, {}
def findall(element: ET.Element, name: str) -> list[ET.Element]:
"""Namespace aware ElementTree.Element.findall()."""
name, namespaces = _namespaced(element, name)
return element.findall(name, namespaces=namespaces)
def find(
element: ET.Element,
name: str,
strict: bool = False,
) -> Optional[ET.Element]:
"""Namespace aware ElementTree.Element.find()."""
name, namespaces = _namespaced(element, name)
elem = element.find(name, namespaces=namespaces)
if strict and elem is None:
raise ValueError(f"XML element <{name}> not found")
return elem
def findtext(
element: ET.Element,
name: str,
strict: bool = False,
default: Optional[str] = None,
) -> Optional[str]:
"""
Namespace aware ElementTree.Element.findtext() with strict flag
raises ValueError if element name not exist.
"""
elem = find(element, name, strict=strict)
return default if elem is None else (elem.text or "")
UnmarshalT = TypeVar("UnmarshalT", bound="UnmarshalProtocol")
class UnmarshalProtocol(Protocol):
"""typing stub for class with `fromxml` method"""
@classmethod
def fromxml(cls: type[UnmarshalT], element: ET.Element) -> UnmarshalT:
"""
Create object by values from XML element.
Code discipline:
1. Do not use find() to look for its own `Element` if needed.
"""
def unmarshal(cls: type[UnmarshalT], xmlstring: str) -> UnmarshalT:
"""Unmarshal given XML string to an object of passed class."""
return cls.fromxml(ET.fromstring(xmlstring))
def getbytes(element: ET.Element) -> bytes:
"""Convert ElementTree.Element to bytes."""
with io.BytesIO() as data:
ET.ElementTree(element).write(
data,
encoding=None,
xml_declaration=False,
)
return data.getvalue()
class MarshalT(Protocol):
"""typing stub for class with `toxml` method"""
def toxml(self, element: Optional[ET.Element]) -> ET.Element:
"""
Convert python object to ElementTree.Element.
Code discipline:
1. Do not create its own `SubElement` if needed.
2. Always return passed `Element`.
3. For root, `element` argument is always `None` hence
root `Element` must be created.
"""
def marshal(obj: MarshalT) -> bytes:
"""Get XML data as bytes of ElementTree.Element."""
return getbytes(obj.toxml(None))