anyconfig.backend.xml.etree

A backend module to load and dump XML files.

  • Format to support: XML, e.g. http://www.w3.org/TR/xml11/

  • Requirements: one of the followings

    • xml.etree.cElementTree in standard lib if python >= 2.5

    • xml.etree.ElementTree in standard lib if python >= 2.5

    • elementtree.ElementTree (otherwise)

  • Development Status :: 4 - Beta

  • Limitations:

    • special node @attrs’, @text’ and @children’ are used to keep XML structure of original data. You have to cusomize them with ‘tags’ keyword option to avoid any config parameters conflict with some of them.

    • Some data or structures of original XML file may be lost if make it backed to XML file; XML file - (anyconfig.load) -> config - (anyconfig.dump) -> XML file

    • XML specific features (namespace, etc.) may not be processed correctly.

  • Special Options:

    • ac_parse_value: Try to parse values, elements’ text and attributes.

    • merge_attrs: Merge attributes and mix with children nodes. Please note that information of attributes are lost after load if this option is used.

    • tags: A dict provide special parameter names to distinguish between attributes, text and children nodes. Default is {“attrs”: “@attrs”, “text”: “@text”, “children”: “@children”}.

Changelog:

Changed in version 0.8.2:

  • Add special options, tags, merge_attrs and ac_parse_value

  • Remove special option, pprefix which conflicts with another option tags

Changed in version 0.8.0:

  • Try to make a nested dict w/o extra dict having keys of attrs, text and children from XML string/file as much as possible.

  • Support namespaces partially.

Changed in version 0.1.0:

  • Added XML dump support.

anyconfig.backend.xml.etree._namespaces_from_file(xmlfile)

Get the namespace str from file.

Parameters:

xmlfile (Union[str, Path, IO]) – XML file or file-like object

Return type:

dict[str, tuple[str, str]]

Returns:

{namespace_uri: namespace_prefix} or {}

anyconfig.backend.xml.etree._tweak_ns(tag, **options)

Tweak the namespace.

Parameters:
  • tag (str) – XML tag element

  • nspaces – A namespaces dict, {uri: prefix}

  • options (dict[str, str]) – Extra keyword options may contain ‘nspaces’ keyword option provide a namespace dict, {uri: prefix}

>>> _tweak_ns("a", nspaces={})
'a'
>>> _tweak_ns("a", nspaces={"http://example.com/ns/val/": "val"})
'a'
:rtype: :sphinx_autodoc_typehints_type:`\:py\:class\:\`str\``
>>> _tweak_ns("{http://example.com/ns/val/}a",
...           nspaces={"http://example.com/ns/val/": "val"})
'val:a'
anyconfig.backend.xml.etree._dicts_have_unique_keys(dics)

Test if given dicts don’t have same keys.

Parameters:

dics (Iterable[dict[str, Any]]) – [<dict or dict-like object>], must not be [] or [{…}]

Return type:

bool

Returns:

True if all keys of each dict of ‘dics’ are unique

# Enable the followings if to allow dics is [], [{…}]: # >>> all(_dicts_have_unique_keys([d]) for [d] # … in ({}, {‘a’: 0}, {‘a’: 1, ‘b’: 0})) # True # >>> _dicts_have_unique_keys([{}, {‘a’: 1}, {‘b’: 2, ‘c’: 0}]) # True

>>> _dicts_have_unique_keys([{}, {"a": 1}, {"a": 2}])
False
>>> _dicts_have_unique_keys([{}, {"a": 1}, {"b": 2}, {"b": 3, "c": 0}])
False
>>> _dicts_have_unique_keys([{}, {}])
True
anyconfig.backend.xml.etree._parse_text(val, **options)

Parse val and interpret its data to some value.

Return type:

Any

Returns:

Parsed value or value itself depends on ‘ac_parse_value’

anyconfig.backend.xml.etree._process_elem_text(elem, dic, subdic, text='@text', **options)

Process the text in the element elem.

Parameters:
  • elem (Element) – ElementTree.Element object which has elem.text

  • dic (dict[str, Any]) – <container> (dict[-like]) object converted from elem

  • subdic (dict[str, Any]) – Sub <container> object converted from elem

  • options – Keyword options, see the description of elem_to_container() for more details.

Return type:

None

Returns:

None but updating elem.text, dic and subdic as side effects

anyconfig.backend.xml.etree._parse_attrs(elem, container=<class 'dict'>, **options)

Parse the attributes of the element elem.

Parameters:
  • elem (Element) – ElementTree.Element object has attributes (elem.attrib)

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

Return type:

dict[str, Any]

Returns:

Parsed value or value itself depends on ‘ac_parse_value’

anyconfig.backend.xml.etree._process_elem_attrs(elem, dic, subdic, container=<class 'dict'>, attrs='@attrs', **options)

Process attributes in the element elem.

Parameters:
  • elem (Element) – ElementTree.Element object or None

  • dic (dict[str, Any]) – <container> (dict[-like]) object converted from elem

  • subdic (dict[str, Any]) – Sub <container> object converted from elem

  • options – Keyword options, see the description of elem_to_container() for more details.

Return type:

None

Returns:

None but updating dic and subdic as side effects

anyconfig.backend.xml.etree._process_children_elems(elem, dic, subdic, container=<class 'dict'>, children='@children', **options)

Process children of the element elem.

Parameters:
  • elem (Element) – ElementTree.Element object or None

  • dic (dict[str, Any]) – <container> (dict[-like]) object converted from elem

  • subdic (dict[str, Any]) – Sub <container> object converted from elem

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • children (str) – Tag for children nodes

  • options – Keyword options, see the description of elem_to_container() for more details.

Return type:

None

Returns:

None but updating dic and subdic as side effects

anyconfig.backend.xml.etree.elem_to_container(elem, container=<class 'dict'>, **options)

Convert XML ElementTree Element to a collection of container objects.

Elements are transformed to a node under special tagged nodes, attrs, text and children, to store the type of these elements basically, however, in some special cases like the followings, these nodes are attached to the parent node directly for later convenience.

  • There is only text element

  • There are only children elements each has unique keys among all

Parameters:
  • elem (Optional[Element]) – ElementTree.Element object or None

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • options

    Keyword options

    • nspaces: A namespaces dict, {uri: prefix} or None

    • attrs, text, children: Tags for special nodes to keep XML info

    • merge_attrs: Merge attributes and mix with children nodes, and the information of attributes are lost after its transformation.

Return type:

dict[str, Any]

anyconfig.backend.xml.etree._complement_tag_options(options)

Complement tag options.

Parameters:

options (dict[str, Any]) – Keyword options :: dict

>>> ref = _TAGS.copy()
>>> ref["text"] = "#text"
>>> opts = _complement_tag_options({"tags": {"text": ref["text"]}})
:rtype: :sphinx_autodoc_typehints_type:`\:py\:class\:\`dict\`\\ \\\[\:py\:class\:\`str\`\, \:py\:data\:\`\~typing.Any\`\]`
>>> del opts["tags"]  # To simplify comparison.
>>> sorted(opts.items())
[('attrs', '@attrs'), ('children', '@children'), ('text', '#text')]
anyconfig.backend.xml.etree.root_to_container(root, container=<class 'dict'>, nspaces=None, **options)

Convert XML ElementTree Root Element to container objects.

Parameters:
  • root (Element) – etree root object or None

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • nspaces (Optional[dict[str, Any]]) – A namespaces dict, {uri: prefix} or None

  • options

    Keyword options,

    • tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {“attrs”: “@attrs”, “text”: “#text”}

Return type:

dict[str, Any]

anyconfig.backend.xml.etree._to_str_fn(**options)

Convert any objects to a str.

Parameters:
  • options (dict[str, Any]) – Keyword options might have ‘ac_parse_value’ key

  • to_str – Callable to convert value to string

Return type:

Callable[..., str]

anyconfig.backend.xml.etree._elem_set_attrs(obj, parent, to_str)

Set attributes of the element parent.

Parameters:
  • obj (dict[str, Any]) – Container instance gives attributes of XML Element

  • parent (Element) – XML ElementTree parent node object

  • to_str (Callable[..., str]) – Callable to convert value to string or None

  • options – Keyword options, see container_to_elem()

Return type:

None

Returns:

None but parent will be modified

anyconfig.backend.xml.etree._elem_from_descendants(children_nodes, **options)

Get the elements from the descendants children_nodes.

Parameters:
  • children_nodes (Iterable[dict[str, Any]]) – A list of child dict objects

  • options – Keyword options, see container_to_elem()

Return type:

Iterator[Element]

anyconfig.backend.xml.etree._get_or_update_parent(key, val, to_str, parent=None, **options)

Get or update the parent element parent.

Parameters:
  • key (str) – Key of current child (dict{,-like} object)

  • val (Any) – Value of current child (dict{,-like} object or [dict{,…}])

  • to_str (Callable[..., str]) – Callable to convert value to string

  • parent (Optional[Element]) – XML ElementTree parent node object or None

  • options – Keyword options, see container_to_elem()

Return type:

Element

anyconfig.backend.xml.etree._assert_if_invalid_node(obj, parent=None)

Make sure the obj or parent is not invalid.

Return type:

None

anyconfig.backend.xml.etree.container_to_elem(obj, parent=None, to_str=None, **options)

Convert a dict-like object to XML ElementTree.

Parameters:
  • obj (Any) – Container instance to convert to

  • parent (Optional[Element]) – XML ElementTree parent node object or None

  • to_str (Optional[Callable[..., str]]) – Callable to convert value to string or None

  • options

    Keyword options,

    • tags: Dict of tags for special nodes to keep XML info, attributes, text and children nodes, e.g. {“attrs”: “@attrs”, “text”: “#text”}

Return type:

Element

anyconfig.backend.xml.etree.etree_write(elem, stream, **options)

Write XML ElementTree ‘root’ content into ‘stream’.

Parameters:
  • tree – XML ElementTree object

  • stream (IO) – File or file-like object can write to

Return type:

None

class anyconfig.backend.xml.etree.Parser

Bases: Parser, ToStreamDumperMixin

Parser for XML files.

_cid: ClassVar[str] = 'xml.etree'
_type: ClassVar[str] = 'xml'
_extensions: tuple[str, ...] = ('xml',)
_load_opts: tuple[str, ...] = ('tags', 'merge_attrs', 'ac_parse_value')
_dump_opts: tuple[str, ...] = ('tags', 'merge_attrs', 'ac_parse_value', 'encoding', 'method', 'xml_declaration', 'default_namespace', 'short_empty_elements')
_ordered: ClassVar[bool] = True
_dict_opts: tuple[str, ...] = ('ac_dict',)
_open_read_mode: ClassVar[str] = 'rb'
_open_write_mode: ClassVar[str] = 'wb'
load_from_string(content, container, **opts)

Load config from XML snippet (a string ‘content’).

Parameters:
  • content (AnyStr) – XML snippet string of str (python 2) or bytes (python 3) type

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • opts – optional keyword parameters passed to

Return type:

dict[str, Any]

Returns:

Dict-like object holding config parameters

load_from_path(filepath, container, **opts)

Load data from path filepath.

Parameters:
  • filepath (Union[str, Path]) – XML file path

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • opts – optional keyword parameters to be sanitized

Return type:

dict[str, Any]

Returns:

Dict-like object holding config parameters

load_from_stream(stream, container, **opts)

Load data from IO stream stream.

Parameters:
  • stream (IO) – XML file or file-like object

  • container (Callable[..., dict[str, Any]]) – callble to make a container object

  • opts – optional keyword parameters to be sanitized

Return type:

dict[str, Any]

Returns:

Dict-like object holding config parameters

dump_to_string(cnf, **opts)

Dump data cnf as a str.

Parameters:
  • cnf (Union[None, int, float, bool, str, dict[str, Any]]) – Configuration data to dump

  • opts – optional keyword parameters

Return type:

bytes

Returns:

string represents the configuration

dump_to_stream(cnf, stream, **opts)

Dump data cnf to the IO stream stream.

Parameters:
  • cnf (Union[None, int, float, bool, str, dict[str, Any]]) – Configuration data to dump

  • stream (IO) – Config file or file like object write to

  • opts – optional keyword parameters

Return type:

None

__annotations__ = {'_allow_primitives': 'typing.ClassVar[bool]', '_cid': 'typing.ClassVar[str]', '_dict_opts': 'tuple[str, ...]', '_dump_opts': 'tuple[str, ...]', '_extensions': 'tuple[str, ...]', '_load_opts': 'tuple[str, ...]', '_open_read_mode': 'typing.ClassVar[str]', '_open_write_mode': 'typing.ClassVar[str]', '_ordered': 'typing.ClassVar[bool]', '_priority': 'typing.ClassVar[int]', '_type': 'typing.ClassVar[str]'}
__module__ = 'anyconfig.backend.xml.etree'