XML 1.0 documents as streams of events (Effect's encoding/Xml).
decode and decode_string turn UTF-8 bytes or text into events, and
encode and encode_string write events back as XML. elements collects
repeated elements, such as the items of a feed, into small trees, so that a large
document is processed one record at a time. to_events turns such a tree back
into events for the encoders.
The decoder checks that documents are well-formed. It never reads external
resources and never expands entities declared in a DOCTYPE, so external entity
(XXE) and entity expansion attacks do not apply. It does not validate against a
DTD or schema, and reports names as written, resolving namespaces only when
asked to (namespaces="strict").
Types#
| Type | Definition | Description |
|---|---|---|
Event | type Event = Declaration | Doctype | StartElement | EndElement | Text | Comment | ProcessingInstruction | What the decoders write and the encoders read. |
XmlErrorKind | type XmlErrorKind = Literal['Syntax', 'Unsupported', 'Limit', 'InvalidEvent'] |
Classes#
Functions#
is_xml_error#
is_xml_error(value) -> TypeIs[XmlError]| Parameter | Type | Description |
|---|---|---|
value | object |
Returns TypeIs[XmlError]
def is_xml_error(value: object) -> TypeIs[XmlError]:
return isinstance(value, XmlError)decode_string#
decode_string[IE = Never, D = None](*, max_token_size=None, max_depth=None, positions=False, namespaces=None) -> Channel[tuple[Event, ...], XmlError | IE, D, tuple[str, ...], IE, D]A channel decoding XML text chunks into events.
Tokens can be split anywhere between chunks, and each output chunk holds the events one input chunk completed. The document must have one root element; whitespace outside it is not reported. A leading byte order mark is skipped, the encoding the declaration names is ignored, and events completed before an error are written before the channel fails.
max_token_size is the most UTF-16 code units one token may take as written
(10 MiB by default), and max_depth the most nested elements (1024);
math.inf disables either, and a limit that is not positive raises
ValueError.
positions=True adds the line and column of each start tag's < to
its StartElement, counted as for XmlError; otherwise they are None.
namespaces="strict" checks the document against Namespaces in XML 1.0 and
adds namespace and local_name to StartElement and EndElement.
A violation fails with "Syntax" at the start tag or processing
instruction, but an undeclared prefix fails with "Unsupported" when the
document has a DOCTYPE, whose declarations are never applied. The
declarations of open elements count against max_token_size.
A DOCTYPE is reported, its internal subset skipped and never applied. An
entity other than the five predefined ones fails with "Unsupported" when
the document has a DOCTYPE and "Syntax" otherwise.
| Parameter | Type | Description |
|---|---|---|
max_token_size | float | None = None | |
max_depth | float | None = None | |
positions | bool = False | |
namespaces | Literal['strict'] | None = None |
Returns Channel[tuple[Event, ...], XmlError | IE, D, tuple[str, ...], IE, D]
def decode_string[IE = Never, D = None](
*,
max_token_size: float | None = None,
max_depth: float | None = None,
positions: bool = False,
namespaces: Literal["strict"] | None = None,
) -> Channel[tuple[Event, ...], XmlError | IE, D, tuple[str, ...], IE, D]:
"""A channel decoding XML text chunks into events.
Tokens can be split anywhere between chunks, and each output chunk holds the
events one input chunk completed. The document must have one root element;
whitespace outside it is not reported. A leading byte order mark is skipped,
the encoding the declaration names is ignored, and events completed before an
error are written before the channel fails.
``max_token_size`` is the most UTF-16 code units one token may take as written
(10 MiB by default), and ``max_depth`` the most nested elements (1024);
``math.inf`` disables either, and a limit that is not positive raises
``ValueError``.
``positions=True`` adds the ``line`` and ``column`` of each start tag's ``<`` to
its ``StartElement``, counted as for ``XmlError``; otherwise they are ``None``.
``namespaces="strict"`` checks the document against Namespaces in XML 1.0 and
adds ``namespace`` and ``local_name`` to ``StartElement`` and ``EndElement``.
A violation fails with ``"Syntax"`` at the start tag or processing
instruction, but an undeclared prefix fails with ``"Unsupported"`` when the
document has a DOCTYPE, whose declarations are never applied. The
declarations of open elements count against ``max_token_size``.
A DOCTYPE is reported, its internal subset skipped and never applied. An
entity other than the five predefined ones fails with ``"Unsupported"`` when
the document has a DOCTYPE and ``"Syntax"`` otherwise."""
parser = _make_parser(max_token_size, max_depth, False, positions, namespaces)
return _make_channel(lambda: TextInput(parser()))decode#
decode[IE = Never, D = None](*, max_token_size=None, max_depth=None, positions=False, namespaces=None) -> Channel[tuple[Event, ...], XmlError | IE, D, tuple[bytes, ...], IE, D]decode_string for UTF-8 bytes. Multi-byte characters can be split
between chunks. Invalid or truncated UTF-8 fails with "Syntax"; a UTF-16
byte order mark, or a declaration naming an encoding other than UTF-8 or
US-ASCII, with "Unsupported" (decode such bytes yourself and use
decode_string). A declaration the bytes contradict fails with "Syntax"
instead: UTF-16, UTF-32, UCS-2 and UCS-4, and US-ASCII or ISO-8859-1 after a
UTF-8 byte order mark.
| Parameter | Type | Description |
|---|---|---|
max_token_size | float | None = None | |
max_depth | float | None = None | |
positions | bool = False | |
namespaces | Literal['strict'] | None = None |
Returns Channel[tuple[Event, ...], XmlError | IE, D, tuple[bytes, ...], IE, D]
def decode[IE = Never, D = None](
*,
max_token_size: float | None = None,
max_depth: float | None = None,
positions: bool = False,
namespaces: Literal["strict"] | None = None,
) -> Channel[tuple[Event, ...], XmlError | IE, D, tuple[bytes, ...], IE, D]:
"""``decode_string`` for UTF-8 bytes. Multi-byte characters can be split
between chunks. Invalid or truncated UTF-8 fails with ``"Syntax"``; a UTF-16
byte order mark, or a declaration naming an encoding other than UTF-8 or
US-ASCII, with ``"Unsupported"`` (decode such bytes yourself and use
``decode_string``). A declaration the bytes contradict fails with ``"Syntax"``
instead: UTF-16, UTF-32, UCS-2 and UCS-4, and US-ASCII or ISO-8859-1 after a
UTF-8 byte order mark."""
parser = _make_parser(max_token_size, max_depth, True, positions, namespaces)
return _make_channel(lambda: Utf8Input(parser()))elements#
elements[IE = Never, D = None](path, *, max_element_size=None) -> Channel[tuple[Element, ...], XmlError | IE, D, tuple[Event, ...], IE, D]A channel collecting the elements at path into trees, to process a large
document one record at a time.
path lists element names from the root, and "*" matches any name. Each
match is written once its end tag arrives, with all its descendants; everything
else is skipped. Whitespace between children is kept as strings.
A name in Clark notation, {uri}local, matches an element by its namespace
and local name, whatever its prefix. {*}local matches the local name in any
namespace or none, and {}local in no namespace. The local name has no prefix
and can't be *. Other names match as written, including prefixes. A path with
a name in Clark notation needs events decoded with namespaces="strict": any
start tag without a local_name fails with "InvalidEvent", even outside a
match. The collected Element has names as written, without namespaces.
A collected element over max_element_size (UTF-16 code units of its names,
attributes and text; 16 MiB by default, math.inf disables it) fails with
"Limit". The size counts characters, not memory, so use a lower limit for
untrusted input. An empty path or an invalid name raises ValueError, and a
str for path, which would read as one name per letter, TypeError.
| Parameter | Type | Description |
|---|---|---|
path | Sequence[str] | |
max_element_size | float | None = None |
Returns Channel[tuple[Element, ...], XmlError | IE, D, tuple[Event, ...], IE, D]
def elements[IE = Never, D = None](
path: Sequence[str], *, max_element_size: float | None = None
) -> Channel[tuple[Element, ...], XmlError | IE, D, tuple[Event, ...], IE, D]:
"""A channel collecting the elements at ``path`` into trees, to process a large
document one record at a time.
``path`` lists element names from the root, and ``"*"`` matches any name. Each
match is written once its end tag arrives, with all its descendants; everything
else is skipped. Whitespace between children is kept as strings.
A name in Clark notation, ``{uri}local``, matches an element by its namespace
and local name, whatever its prefix. ``{*}local`` matches the local name in any
namespace or none, and ``{}local`` in no namespace. The local name has no prefix
and can't be ``*``. Other names match as written, including prefixes. A path with
a name in Clark notation needs events decoded with ``namespaces="strict"``: any
start tag without a ``local_name`` fails with ``"InvalidEvent"``, even outside a
match. The collected ``Element`` has names as written, without namespaces.
A collected element over ``max_element_size`` (UTF-16 code units of its names,
attributes and text; 16 MiB by default, ``math.inf`` disables it) fails with
``"Limit"``. The size counts characters, not memory, so use a lower limit for
untrusted input. An empty path or an invalid name raises ``ValueError``, and a
``str`` for ``path``, which would read as one name per letter, ``TypeError``."""
if isinstance(path, str):
raise TypeError(f"Xml: elements path must be a sequence of names, got {quoted(path)}")
if not path:
raise ValueError("Xml: elements path must not be empty")
segments = tuple(parse_segment(name) for name in path)
limit = _check_limit("maxElementSize", max_element_size, _DEFAULT_MAX_ELEMENT_SIZE)
return _make_channel(lambda: Collector(segments, limit))encode_string#
encode_string[IE = Never, D = None]() -> Channel[tuple[str, ...], XmlError | IE, D, tuple[Event, ...], IE, D]A channel writing events as XML text, one string per input chunk.
Text escapes &, < and >; attribute values are double-quoted and
escape &, <, ", tabs and line breaks. Empty elements use explicit
closing tags (<br></br>), and nothing is added between events.
Events that do not form one well-formed document fail with "InvalidEvent",
and the stream must end with the root element closed.
Returns Channel[tuple[str, ...], XmlError | IE, D, tuple[Event, ...], IE, D]
def encode_string[IE = Never, D = None]() -> Channel[
tuple[str, ...], XmlError | IE, D, tuple[Event, ...], IE, D
]:
"""A channel writing events as XML text, one string per input chunk.
Text escapes ``&``, ``<`` and ``>``; attribute values are double-quoted and
escape ``&``, ``<``, ``"``, tabs and line breaks. Empty elements use explicit
closing tags (``<br></br>``), and nothing is added between events.
Events that do not form one well-formed document fail with ``"InvalidEvent"``,
and the stream must end with the root element closed."""
return _make_channel(lambda: Writer(False))encode#
encode[IE = Never, D = None]() -> Channel[tuple[bytes, ...], XmlError | IE, D, tuple[Event, ...], IE, D]encode_string as UTF-8 bytes. A Declaration naming another encoding
fails with "InvalidEvent".
Returns Channel[tuple[bytes, ...], XmlError | IE, D, tuple[Event, ...], IE, D]
def encode[IE = Never, D = None]() -> Channel[
tuple[bytes, ...], XmlError | IE, D, tuple[Event, ...], IE, D
]:
"""``encode_string`` as UTF-8 bytes. A ``Declaration`` naming another encoding
fails with ``"InvalidEvent"``."""
channel: Any = _make_channel(lambda: Writer(True))
def to_bytes(chunk: tuple[str, ...]) -> tuple[bytes, ...]:
return tuple(text_encode(text) for text in chunk)
return channel.map(to_bytes)to_events#
to_events(element) -> tuple[Event, *(tuple[Event, ...])]element as events: its start tag, the events of its children in
order, and its end tag. Each string child is one Text, even an empty one.
Names and characters are not checked; the encoders check them.
A collected subtree does not carry the xmlns declarations it inherited,
so supply the same bindings on it, or around it, when writing it elsewhere::
note = Element("note", {"id": "1"}, ("Hi ", Element("b", {}, ("there",))))
stream.from_iterable(to_events(note)).pipe_through_channel(encode_string())
# '<note id="1">Hi <b>there</b></note>'| Parameter | Type | Description |
|---|---|---|
element | Element |
Returns tuple[Event, *(tuple[Event, ...])]
def to_events(element: Element) -> tuple[Event, *tuple[Event, ...]]:
"""``element`` as events: its start tag, the events of its children in
order, and its end tag. Each string child is one ``Text``, even an empty one.
Names and characters are not checked; the encoders check them.
A collected subtree does not carry the ``xmlns`` declarations it inherited,
so supply the same bindings on it, or around it, when writing it elsewhere::
note = Element("note", {"id": "1"}, ("Hi ", Element("b", {}, ("there",))))
stream.from_iterable(to_events(note)).pipe_through_channel(encode_string())
# '<note id="1">Hi <b>there</b></note>'
"""
first: Event = StartElement(element.name, element.attributes)
out: list[Event] = []
# Each open element and the index of its next child, so depth costs no stack
stack: list[tuple[Element, int]] = [(element, 0)]
while stack:
current, index = stack[-1]
if index == len(current.children):
out.append(EndElement(current.name))
stack.pop()
continue
stack[-1] = (current, index + 1)
child = current.children[index]
if isinstance(child, str):
out.append(Text(child))
else:
out.append(StartElement(child.name, child.attributes))
stack.append((child, 0))
return (first, *out)