Script 'mail_helper' called by obssrc Hello community, here is the log from the commit of package python-xmltodict for openSUSE:Factory checked in at 2026-12-05 19:09:37 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-xmltodict (Old) and /work/SRC/openSUSE:Factory/.python-xmltodict.new.1340718 (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-xmltodict" Sat Dec 5 19:09:37 2026 rev:18 rq:1402956 version:1.0.5 Changes: -------- --- /work/SRC/openSUSE:Factory/python-xmltodict/python-xmltodict.changes 2026-03-15 14:31:53.466212901 +0100 +++ /work/SRC/openSUSE:Factory/.python-xmltodict.new.1340718/python-xmltodict.changes 2026-12-05 19:10:37.407727309 +0100 @@ -1,0 +2,13 @@ +Wed Dec 2 11:48:55 UTC 2026 - Martin Hauke <[email protected]> + +- Update to version 1.0.5 + Bug Fixes + * parse: preserve missing-key dict values (#435). + * streaming: preserve #text on streamed items (#421). + * unparse: honor custom attr_prefix for xmlns declaration dicts + (#422). + * unparse: preserve exact namespace URI keys (#431). + * unparse: preserve literal comment text (#423). + * unparse: preserve mapping values (#433). + +------------------------------------------------------------------- Old: ---- xmltodict-1.0.4.tar.gz New: ---- xmltodict-1.0.5.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-xmltodict.spec ++++++ --- /var/tmp/diff_new_pack.uQpZFr/_old 2026-12-05 19:10:38.192760391 +0100 +++ /var/tmp/diff_new_pack.uQpZFr/_new 2026-12-05 19:10:38.195760518 +0100 @@ -18,7 +18,7 @@ %{?sle15_python_module_pythons} Name: python-xmltodict -Version: 1.0.4 +Version: 1.0.5 Release: 0 Summary: Module to make XML working resemble JSON License: MIT ++++++ xmltodict-1.0.4.tar.gz -> xmltodict-1.0.5.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/PKG-INFO new/xmltodict-1.0.5/PKG-INFO --- old/xmltodict-1.0.4/PKG-INFO 2026-02-22 03:21:09.137860300 +0100 +++ new/xmltodict-1.0.5/PKG-INFO 2026-12-02 08:16:25.355711000 +0100 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: xmltodict -Version: 1.0.4 +Version: 1.0.5 Summary: Makes working with XML feel like you are working with JSON Author: Martin Blech License-Expression: MIT @@ -76,6 +76,11 @@ ... """ >>> xmltodict.parse(xml, process_namespaces=True) == { ... 'http://defaultns.com/:root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'http://defaultns.com/:x': '1', ... 'http://a.com/:y': '2', ... 'http://b.com/:z': '3', @@ -93,6 +98,11 @@ ... } >>> xmltodict.parse(xml, process_namespaces=True, namespaces=namespaces) == { ... 'root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'x': '1', ... 'ns_a:y': '2', ... 'http://b.com/:z': '3', @@ -241,7 +251,7 @@ - `cdata_separator=''`: Separator string to join multiple text nodes. This joins adjacent text nodes. For example, set to a space to avoid concatenation. - `postprocessor=None`: Function to modify parsed items. - `dict_constructor=dict`: Constructor for dictionaries (e.g., dict). -- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. +- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. If you preserve whitespace text nodes, avoid combining this with `unparse(..., pretty=True)`: the preserved text nodes and pretty-print indentation/newlines will both be emitted. - `namespaces=None`: Mapping of namespaces to prefixes, or None to keep full URIs. - `force_list=None`: Force list values for specific elements. Can be a boolean (True/False), a tuple of element names to force lists for, or a callable function that receives (path, key, value) and returns True/False. Useful for elements that may appear once or multiple times to ensure consistent list output. - `item_depth=0`: Depth at which to call `item_callback`. @@ -252,7 +262,7 @@ Convert a Python dictionary back into XML. -- `input_dict`: Dictionary to convert to XML. +- `input_dict`: Dictionary or other `collections.abc.Mapping` to convert to XML. Nested mappings, including those produced by `parse(..., dict_constructor=collections.UserDict)`, are supported. - `output=None`: File-like object to write XML to; returns string if None. - `encoding='utf-8'`: Encoding of the output XML. - `bytes_errors='replace'`: Error handler used when decoding byte values during unparse (for example `'replace'`, `'strict'`, `'ignore'`). @@ -260,8 +270,8 @@ - `short_empty_elements=False`: Use short tags for empty elements (`<tag/>`). - `attr_prefix='@'`: Prefix for dictionary keys representing attributes. - `cdata_key='#text'`: Key for text content in the dictionary. -- `pretty=False`: Pretty-print the XML output. -- `indent='\t'`: Indentation string for pretty printing. +- `pretty=False`: Pretty-print the XML output. This adds indentation/newlines for readability, so it should generally not be combined with parsed whitespace-preserving content when exact round-tripping matters. +- `indent='\t'`: Indentation string for pretty printing. May also be an integer number of spaces. - `newl='\n'`: Newline character for pretty printing. - `expand_iter=None`: Tag name to use for items in nested lists (breaks roundtripping). diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/README.md new/xmltodict-1.0.5/README.md --- old/xmltodict-1.0.4/README.md 2026-02-22 03:21:02.000000000 +0100 +++ new/xmltodict-1.0.5/README.md 2026-12-02 08:16:19.374633000 +0100 @@ -49,6 +49,11 @@ ... """ >>> xmltodict.parse(xml, process_namespaces=True) == { ... 'http://defaultns.com/:root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'http://defaultns.com/:x': '1', ... 'http://a.com/:y': '2', ... 'http://b.com/:z': '3', @@ -66,6 +71,11 @@ ... } >>> xmltodict.parse(xml, process_namespaces=True, namespaces=namespaces) == { ... 'root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'x': '1', ... 'ns_a:y': '2', ... 'http://b.com/:z': '3', @@ -214,7 +224,7 @@ - `cdata_separator=''`: Separator string to join multiple text nodes. This joins adjacent text nodes. For example, set to a space to avoid concatenation. - `postprocessor=None`: Function to modify parsed items. - `dict_constructor=dict`: Constructor for dictionaries (e.g., dict). -- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. +- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. If you preserve whitespace text nodes, avoid combining this with `unparse(..., pretty=True)`: the preserved text nodes and pretty-print indentation/newlines will both be emitted. - `namespaces=None`: Mapping of namespaces to prefixes, or None to keep full URIs. - `force_list=None`: Force list values for specific elements. Can be a boolean (True/False), a tuple of element names to force lists for, or a callable function that receives (path, key, value) and returns True/False. Useful for elements that may appear once or multiple times to ensure consistent list output. - `item_depth=0`: Depth at which to call `item_callback`. @@ -225,7 +235,7 @@ Convert a Python dictionary back into XML. -- `input_dict`: Dictionary to convert to XML. +- `input_dict`: Dictionary or other `collections.abc.Mapping` to convert to XML. Nested mappings, including those produced by `parse(..., dict_constructor=collections.UserDict)`, are supported. - `output=None`: File-like object to write XML to; returns string if None. - `encoding='utf-8'`: Encoding of the output XML. - `bytes_errors='replace'`: Error handler used when decoding byte values during unparse (for example `'replace'`, `'strict'`, `'ignore'`). @@ -233,8 +243,8 @@ - `short_empty_elements=False`: Use short tags for empty elements (`<tag/>`). - `attr_prefix='@'`: Prefix for dictionary keys representing attributes. - `cdata_key='#text'`: Key for text content in the dictionary. -- `pretty=False`: Pretty-print the XML output. -- `indent='\t'`: Indentation string for pretty printing. +- `pretty=False`: Pretty-print the XML output. This adds indentation/newlines for readability, so it should generally not be combined with parsed whitespace-preserving content when exact round-tripping matters. +- `indent='\t'`: Indentation string for pretty printing. May also be an integer number of spaces. - `newl='\n'`: Newline character for pretty printing. - `expand_iter=None`: Tag name to use for items in nested lists (breaks roundtripping). diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/pyproject.toml new/xmltodict-1.0.5/pyproject.toml --- old/xmltodict-1.0.4/pyproject.toml 2026-02-22 03:21:02.000000000 +0100 +++ new/xmltodict-1.0.5/pyproject.toml 2026-12-02 08:16:19.374633000 +0100 @@ -4,7 +4,7 @@ [project] name = "xmltodict" -version = "1.0.4" +version = "1.0.5" description = "Makes working with XML feel like you are working with JSON" readme = "README.md" requires-python = ">=3.9" diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/tests/test_dicttoxml.py new/xmltodict-1.0.5/tests/test_dicttoxml.py --- old/xmltodict-1.0.4/tests/test_dicttoxml.py 2026-02-22 03:21:02.000000000 +0100 +++ new/xmltodict-1.0.5/tests/test_dicttoxml.py 2026-12-02 08:16:19.375300600 +0100 @@ -2,6 +2,8 @@ import pytest import re from textwrap import dedent +from collections import ChainMap, UserDict +from types import MappingProxyType _HEADER_RE = re.compile(r'^[^\n]*\n') @@ -98,6 +100,59 @@ assert unparse(obj) == unparse(parse(unparse(obj))) [email protected]('mapping_type', [UserDict, ChainMap, MappingProxyType]) [email protected]('expand_iter', [None, 'item']) [email protected]('short_empty_elements', [False, True]) +def test_mapping_values(mapping_type, expand_iter, short_empty_elements): + obj = {'root': mapping_type({ + '@id': 7, + 'child': [mapping_type({'@active': True, '#text': b'value'}), + mapping_type({})], + })} + xml = unparse(obj, expand_iter=expand_iter, + short_empty_elements=short_empty_elements) + assert parse(xml) == {'root': { + '@id': '7', + 'child': [{'@active': 'true', '#text': 'value'}, None], + }} + + [email protected]('xml', [ + '<root><child>value</child></root>', + '<root id="7"><child>one</child><child>two</child></root>', + '<root><child active="true">value</child><empty/></root>', +]) +def test_userdict_constructor_roundtrip(xml): + obj = parse(xml, dict_constructor=UserDict) + assert parse(unparse(obj)) == parse(xml) + + +def test_userdict_constructor_namespace_roundtrip(): + xml = '<root xmlns:n="urn:example"><n:child n:id="7">value</n:child></root>' + obj = parse(xml, process_namespaces=True, dict_constructor=UserDict) + result = unparse(obj, namespaces={'urn:example': 'n'}) + assert parse(result, process_namespaces=True) == parse(xml, process_namespaces=True) + + [email protected]('mapping_type', [UserDict, ChainMap, MappingProxyType]) +def test_mapping_namespace_declarations(mapping_type): + obj = {'root': { + '@xmlns': mapping_type({'n': 'urn:example'}), + 'n:child': 'value', + }} + assert parse(unparse(obj), process_namespaces=True) == { + 'root': {'@xmlns': {'n': 'urn:example'}, + 'urn:example:child': 'value'}, + } + + [email protected]('mapping_type', [UserDict, ChainMap, MappingProxyType]) [email protected]('key', ['bad>name', '@bad>name']) +def test_mapping_names_are_validated(mapping_type, key): + with pytest.raises(ValueError, match='Invalid .* name'): + unparse({'root': mapping_type({key: 'value'})}) + + def test_semistructured(): xml = '<a>abc<d/>efg</a>' assert _strip(unparse(parse(xml))) == '<a><d></d>abcefg</a>' @@ -326,6 +381,83 @@ assert xml == '<root xmlns:a="true"></root>' +def test_xmlns_dict_honors_custom_attr_prefix(): + # A namespace-declaration dict must be recognized under a custom + # attr_prefix, like every other attribute — otherwise unparse cannot + # round-trip what parse(..., attr_prefix="!") produced. + xml = unparse( + {"root": {"!xmlns": {"a": "http://a.com/"}, "!id": "7"}}, + attr_prefix="!", + full_document=False, + ) + assert xml == '<root xmlns:a="http://a.com/" id="7"></root>' + + +def test_namespace_roundtrip_honors_custom_attr_prefix(): + obj = parse( + '<root xmlns:a="http://a.com/" id="7"><a:y>2</a:y></root>', + process_namespaces=True, + attr_prefix="!", + ) + + xml = unparse( + obj, + attr_prefix="!", + namespaces={"http://a.com/": "a"}, + full_document=False, + ) + + assert xml == '<root id="7" xmlns:a="http://a.com/"><a:y>2</a:y></root>' + + [email protected]('attr_prefix, namespace', [ + ('@', 'urn:example@'), + ('@@', 'urn:example@@'), + ('_', 'urn:example_'), + ('attr_', 'urn:test'), + ('http', 'http://example.com/http'), + ('urn', 'urn:example'), + ('u_', 'urn:example'), + ('@', 'http://example.com/'), +]) [email protected]('short_empty_elements', [False, True]) +def test_namespace_uri_preserved_with_attr_prefix( + attr_prefix, namespace, short_empty_elements): + original = ( + '<p:root xmlns:p="{}" p:code="x">' + '<child id="y"/></p:root>' + ).format(namespace) + options = dict(process_namespaces=True, attr_prefix=attr_prefix) + obj = parse(original, **options) + + xml = unparse(obj, attr_prefix=attr_prefix, namespaces={namespace: 'p'}, + short_empty_elements=short_empty_elements) + + assert parse(xml, **options) == obj + assert '<p:root p:code="x"' in xml + + [email protected]('attr_prefix, namespace', [ + ('@', 'urn:example@'), + ('@@', 'urn:example@@'), + ('_', 'urn:example_'), + ('attr_', 'urn:test'), + ('u_', 'urn:example'), + ('@', 'http://example.com/'), +]) +def test_nested_namespace_uri_preserved_with_attr_prefix(attr_prefix, namespace): + original = ( + '<root xmlns:p="{}"><p:child p:code="x"/></root>' + ).format(namespace) + options = dict(process_namespaces=True, attr_prefix=attr_prefix) + obj = parse(original, **options) + + xml = unparse(obj, attr_prefix=attr_prefix, namespaces={namespace: 'p'}) + + assert parse(xml, **options) == obj + assert '<p:child p:code="x"' in xml + + def test_xmlns_values_decode_bytes_with_output_encoding(): xml = unparse( {"root": {"@xmlns": {"a": b"http://ex\xe9.com/"}}}, @@ -710,3 +842,59 @@ def test_none_attribute_serializes_as_empty_string(): assert unparse({"x": {"@pro": None}}, full_document=False) == '<x pro=""></x>' + + +def test_unparse_skips_none_comment(): + obj = {"a": {"#comment": None, "b": "1"}} + xml = _strip(unparse(obj, full_document=True)) + assert xml == "<a><b>1</b></a>" + + +def test_unparse_skips_empty_comment(): + obj = {"a": {"#comment": "", "b": "1"}} + xml = _strip(unparse(obj, full_document=True)) + assert xml == "<a><b>1</b></a>" + + +def test_unparse_filters_none_and_empty_comments_in_list(): + obj = {"a": {"#comment": ["n1", None, "", "n2"], "b": "1"}} + xml = _strip(unparse(obj, full_document=True)) + assert xml == "<a><!--n1--><!--n2--><b>1</b></a>" + + +def test_pretty_print_element_comments(): + obj = {"a": {"#comment": ["n1", "n2"], "b": "1"}} + xml = dedent('''\ + <?xml version="1.0" encoding="utf-8"?> + <a> + \t<!--n1--> + \t<!--n2--> + \t<b>1</b> + </a>''') + assert xml == unparse(obj, pretty=True) + + +def test_pretty_print_top_level_comment_with_int_indent(): + obj = {"#comment": "top", "a": "1"} + xml = dedent('''\ + <?xml version="1.0" encoding="utf-8"?> + <!--top--> + <a>1</a>''') + assert xml == unparse(obj, pretty=True, indent=4) + + +def test_unparse_comment_does_not_escape_special_chars(): + """Comments must not have their content XML-escaped; & and < are literal in comments.""" + obj = {"a": {"#comment": "a & b < c > d", "b": "1"}} + result = unparse(obj) + assert "<!--a & b < c > d-->" in result + # Verify round-trip preserves all special chars including quotes + parsed = parse(result, process_comments=True) + assert parsed["a"]["#comment"] == "a & b < c > d" + + # Also test quotes and > in comments + obj2 = {"a": {"#comment": 'say "hello" & \'bye\'', "b": "1"}} + result2 = unparse(obj2) + assert "<!--say \"hello\" & 'bye'-->" in result2 + parsed2 = parse(result2, process_comments=True) + assert parsed2["a"]["#comment"] == 'say "hello" & \'bye\'' diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/tests/test_xmltodict.py new/xmltodict-1.0.5/tests/test_xmltodict.py --- old/xmltodict-1.0.4/tests/test_xmltodict.py 2026-02-22 03:21:02.000000000 +0100 +++ new/xmltodict-1.0.5/tests/test_xmltodict.py 2026-12-02 08:16:19.375300600 +0100 @@ -187,6 +187,93 @@ assert result is None +def _stream(xml, depth, **kwargs): + items = [] + parse(xml, item_depth=depth, + item_callback=lambda path, item: items.append(item) or True, + **kwargs) + return items + + +def test_streaming_text_with_attrs(): + # char data was dropped when the streamed item had attributes (#257) + xml = '<items><item id="1">hello</item></items>' + assert _stream(xml, 2) == [{'@id': '1', '#text': 'hello'}] + + +def test_streaming_text_postprocessor(): + def postprocessor(path, key, value): + if key == '#text': + assert path == [('items', None), ('item', {'id': '1'})] + return 'text', value.upper() + return key, value + + xml = '<items><item id="1">hello</item></items>' + assert _stream(xml, 2, postprocessor=postprocessor) == \ + [{'@id': '1', 'text': 'HELLO'}] + + +def test_streaming_text_with_children(): + xml = '<a>free text<b>1</b><b>2</b></a>' + assert _stream(xml, 1) == [{'b': ['1', '2'], '#text': 'free text'}] + xml = '<items><item><sub>x</sub>tail</item></items>' + assert _stream(xml, 2) == [{'sub': 'x', '#text': 'tail'}] + + +def test_streaming_text_whitespace(): + xml = '<items><item id="1"> spaced </item></items>' + assert _stream(xml, 2) == [{'@id': '1', '#text': 'spaced'}] + assert _stream(xml, 2, strip_whitespace=False) == \ + [{'@id': '1', '#text': ' spaced '}] + # whitespace-only text is stripped to nothing, like non-streaming parse + xml = '<items><item id="1"> </item></items>' + assert _stream(xml, 2) == [{'@id': '1'}] + + +def test_streaming_force_cdata_and_cdata_key(): + xml = '<items><item>x</item></items>' + assert _stream(xml, 2, force_cdata=True) == [{'#text': 'x'}] + xml = '<items><item id="1">x</item></items>' + assert _stream(xml, 2, cdata_key='$') == [{'@id': '1', '$': 'x'}] + + +def test_streaming_matches_nonstreaming(): + docs = [ + '<r><item>plain</item></r>', + '<r><item id="1">text</item><item>only</item></r>', + '<r><item a="1"><c>x</c>tail</item><item a="2">lead<c>y</c></item></r>', + '<r><item><sub><deep d="3">v</deep></sub>mixed</item></r>', + '<r><item> </item><item id="1"> </item></r>', + ] + for xml in docs: + expected = parse(xml)['r']['item'] + if not isinstance(expected, list): + expected = [expected] + assert _stream(xml, 2) == expected, xml + + +def test_streaming_random_docs_match_nonstreaming(): + import random + rnd = random.Random(20260715) + for _ in range(200): + items = [] + for i in range(rnd.randint(1, 4)): + attr = f' id="{i}"' if rnd.random() < 0.5 else '' + children = ''.join(f'<c{j}>v{j}</c{j}>' + for j in range(rnd.randint(0, 2))) + text = rnd.choice(['', ' ', 'txt', 'a b']) + if rnd.random() < 0.5: + body = text + children + else: + body = children + text + items.append(f'<item{attr}>{body}</item>') + xml = f"<r>{''.join(items)}</r>" + expected = parse(xml)['r']['item'] + if not isinstance(expected, list): + expected = [expected] + assert _stream(xml, 2) == expected, xml + + def test_postprocessor(): def postprocessor(path, key, value): try: @@ -627,3 +714,31 @@ } } assert parse(xml, process_namespaces=True, namespaces=namespaces) == expected + + +def test_force_list_true_applies_to_all_keys(): + xml = "<a><b>1</b><b>2</b><c>x</c></a>" + expected = {"a": [{"b": ["1", "2"], "c": ["x"]}]} + assert parse(xml, force_list=True) == expected + + +def test_defaultdict_constructor_does_not_create_missing_values(): + from collections import defaultdict + from functools import partial + + for factory in (dict, list): + result = parse('<a id="x"><b>1</b><b>2</b><c>3</c></a>', + dict_constructor=partial(defaultdict, factory)) + assert result == {'a': {'@id': 'x', 'b': ['1', '2'], 'c': '3'}} + assert isinstance(result, defaultdict) + assert isinstance(result['a'], defaultdict) + + +def test_defaultdict_constructor_with_force_list_and_postprocessor(): + from collections import defaultdict + from functools import partial + + result = parse('<a><b>1</b><c>2</c></a>', + dict_constructor=partial(defaultdict, dict), + force_list=('b',), postprocessor=lambda p, k, v: (k, v) if k != 'c' else None) + assert result == {'a': {'b': ['1']}} diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/xmltodict.egg-info/PKG-INFO new/xmltodict-1.0.5/xmltodict.egg-info/PKG-INFO --- old/xmltodict-1.0.4/xmltodict.egg-info/PKG-INFO 2026-02-22 03:21:09.000000000 +0100 +++ new/xmltodict-1.0.5/xmltodict.egg-info/PKG-INFO 2026-12-02 08:16:25.345244200 +0100 @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: xmltodict -Version: 1.0.4 +Version: 1.0.5 Summary: Makes working with XML feel like you are working with JSON Author: Martin Blech License-Expression: MIT @@ -76,6 +76,11 @@ ... """ >>> xmltodict.parse(xml, process_namespaces=True) == { ... 'http://defaultns.com/:root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'http://defaultns.com/:x': '1', ... 'http://a.com/:y': '2', ... 'http://b.com/:z': '3', @@ -93,6 +98,11 @@ ... } >>> xmltodict.parse(xml, process_namespaces=True, namespaces=namespaces) == { ... 'root': { +... '@xmlns': { +... '': 'http://defaultns.com/', +... 'a': 'http://a.com/', +... 'b': 'http://b.com/', +... }, ... 'x': '1', ... 'ns_a:y': '2', ... 'http://b.com/:z': '3', @@ -241,7 +251,7 @@ - `cdata_separator=''`: Separator string to join multiple text nodes. This joins adjacent text nodes. For example, set to a space to avoid concatenation. - `postprocessor=None`: Function to modify parsed items. - `dict_constructor=dict`: Constructor for dictionaries (e.g., dict). -- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. +- `strip_whitespace=True`: Remove leading/trailing whitespace in text nodes. Default is True; this trims whitespace in text nodes. Set to False to preserve whitespace exactly. When `process_comments=True`, this same flag also trims comment text; disable `strip_whitespace` if you need to preserve comment indentation or padding. If you preserve whitespace text nodes, avoid combining this with `unparse(..., pretty=True)`: the preserved text nodes and pretty-print indentation/newlines will both be emitted. - `namespaces=None`: Mapping of namespaces to prefixes, or None to keep full URIs. - `force_list=None`: Force list values for specific elements. Can be a boolean (True/False), a tuple of element names to force lists for, or a callable function that receives (path, key, value) and returns True/False. Useful for elements that may appear once or multiple times to ensure consistent list output. - `item_depth=0`: Depth at which to call `item_callback`. @@ -252,7 +262,7 @@ Convert a Python dictionary back into XML. -- `input_dict`: Dictionary to convert to XML. +- `input_dict`: Dictionary or other `collections.abc.Mapping` to convert to XML. Nested mappings, including those produced by `parse(..., dict_constructor=collections.UserDict)`, are supported. - `output=None`: File-like object to write XML to; returns string if None. - `encoding='utf-8'`: Encoding of the output XML. - `bytes_errors='replace'`: Error handler used when decoding byte values during unparse (for example `'replace'`, `'strict'`, `'ignore'`). @@ -260,8 +270,8 @@ - `short_empty_elements=False`: Use short tags for empty elements (`<tag/>`). - `attr_prefix='@'`: Prefix for dictionary keys representing attributes. - `cdata_key='#text'`: Key for text content in the dictionary. -- `pretty=False`: Pretty-print the XML output. -- `indent='\t'`: Indentation string for pretty printing. +- `pretty=False`: Pretty-print the XML output. This adds indentation/newlines for readability, so it should generally not be combined with parsed whitespace-preserving content when exact round-tripping matters. +- `indent='\t'`: Indentation string for pretty printing. May also be an integer number of spaces. - `newl='\n'`: Newline character for pretty printing. - `expand_iter=None`: Tag name to use for items in nested lists (breaks roundtripping). diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/xmltodict-1.0.4/xmltodict.py new/xmltodict-1.0.5/xmltodict.py --- old/xmltodict-1.0.4/xmltodict.py 2026-02-22 03:21:02.000000000 +0100 +++ new/xmltodict-1.0.5/xmltodict.py 2026-12-02 08:16:19.375300600 +0100 @@ -2,10 +2,11 @@ "Makes working with XML feel like you are working with JSON" from xml.parsers import expat -from xml.sax.saxutils import XMLGenerator, escape +from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesImpl from io import StringIO from inspect import isgenerator +from collections.abc import Mapping import codecs class ParsingInterrupted(Exception): @@ -107,10 +108,18 @@ # without attaching it back to its parent. This avoids accumulating all # streamed items in memory when using item_depth > 0. if len(self.path) == self.item_depth: + data = (None if not self.data + else self.cdata_separator.join(self.data)) item = self.item - if item is None: - item = (None if not self.data - else self.cdata_separator.join(self.data)) + if self.strip_whitespace and data: + data = data.strip() or None + if data and self._should_force_cdata(name, data) and item is None: + item = self.dict_constructor() + if item is not None: + if data: + self.push_data(item, self.cdata_key, data) + else: + item = data should_continue = self.item_callback(self.path, item) if not should_continue: @@ -163,13 +172,13 @@ key, data = result if item is None: item = self.dict_constructor() - try: + if key in item: value = item[key] if isinstance(value, list): value.append(data) else: item[key] = [value, data] - except KeyError: + else: if self._should_force_list(key, data): item[key] = [data] else: @@ -432,7 +441,8 @@ except ValueError: pass else: - ns_res = namespaces.get(ns.strip(attr_prefix)) + ns_res = namespaces.get( + ns[len(attr_prefix):] if ns.startswith(attr_prefix) else ns) name = '{}{}{}{}'.format( attr_prefix if ns.startswith(attr_prefix) else '', ns_res, ns_sep, name) if ns_res else name @@ -473,7 +483,7 @@ content_handler.ignorableWhitespace(newl) return - key = _process_namespace(key, namespaces, namespace_separator, attr_prefix) + key = _process_namespace(key, namespaces, namespace_separator, '') if preprocessor is not None: result = preprocessor(key, value) if result is None: @@ -481,14 +491,14 @@ key, value = result # Minimal validation to avoid breaking out of tag context _validate_name(key, "element") - if not hasattr(value, '__iter__') or isinstance(value, (str, bytes, bytearray, memoryview, dict)): + if not hasattr(value, '__iter__') or isinstance(value, (str, bytes, bytearray, memoryview, Mapping)): value = [value] for index, v in enumerate(value): if full_document and depth == 0 and index > 0: raise ValueError('document with multiple roots') if v is None: v = {} - elif not isinstance(v, (dict, str)): + elif not isinstance(v, (Mapping, str)): if expand_iter and hasattr(v, '__iter__') and not isinstance(v, (bytes, bytearray, memoryview)): v = {expand_iter: v} else: @@ -508,7 +518,7 @@ if isinstance(ik, str) and ik.startswith(attr_prefix): ik = _process_namespace(ik, namespaces, namespace_separator, attr_prefix) - if ik == '@xmlns' and isinstance(iv, dict): + if ik == attr_prefix + 'xmlns' and isinstance(iv, Mapping): for k, v in iv.items(): _validate_name(k, "attribute") attr = 'xmlns{}'.format(f':{k}' if k else '') @@ -553,7 +563,7 @@ class _XMLGenerator(XMLGenerator): def comment(self, text): text = _validate_comment(text) - self._write(f"<!--{escape(text)}-->") + self._write(f"<!--{text}-->") def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
