API

Module contents

class mappet.Mappet(xml)[source]

Bases: mappet.mappet.Node

A node that may have children.

assign_dict(node, xml_dict)[source]

Assigns a Python dict to a lxml node.

Parameters:
  • node – A node to assign the dict to.
  • xml_dict – The dict with attributes/children to use.
static assign_literal(element, value)[source]

Assigns a literal.

If a given node doesn’t exist, it will be created.

Parameters:
  • element (etree.Element) – element to which we assign.
  • value – the value to assign
static assign_sequence_or_set(element, value)[source]
children(key=None)[source]

Returns node’s children.

Parameters:key – A key for filtering children by tagname.
create(tag, value)[source]

Creates a node, if it doesn’t exist yet.

Unlike attribute access, this allows to pass a node’s name with hyphens. Those hyphens will be normalized automatically.

In case the required element already exists, raises an exception. Updating/overwriting should be done using update`.

has_children()[source]

Returns true if a node has children.

iter_children(key=None)[source]

Iterates over children.

Parameters:key – A key for filtering children by tagname.
keys()[source]

Returns a set of node’s keys.

set(name, value)[source]

Assigns a new XML structure to the node.

A literal value, dict or list can be passed in. Works for all nested levels.

Dictionary: >>> m = Mappet(‘<root/>’) >>> m.head = {‘a’: ‘A’, ‘b’: {‘#text’: ‘B’, '@attr‘: ‘val’}} >>> m.head.to_str() ‘<head><a>A</a><b attr=”val”>B</b></head>’

List: >>> m.head = [{‘a’: i} for i in ‘ABC’] >>> m.head.to_str() ‘<head><a>A</a><a>B</a><a>C</a></head>’

Literals: >>> m.head.leaf = ‘A’ >>> m.head.leaf.get() ‘A’

sget(path, default=NONE_NODE)[source]

Enables access to nodes if one or more of them don’t exist.

Example: >>> m = Mappet(‘<root><tag attr1=”attr text”>text value</tag></root>’) >>> m.sget(‘tag’) text value >>> m.sget(‘tag.@attr1’) ‘attr text’ >>> m.sget(‘tag.#text’) ‘text value’ >>> m.sget(‘reply.vms_model_cars.car.0.params.doors’) NONE_NODE

Accessing nonexistent path returns None-like object with mocked converting functions which returns None: >>> m.sget(‘reply.fake_node’).to_dict() is None True

to_dict(**kw)[source]

Converts the lxml object to a dict.

possible kwargs:
without_comments: bool
to_str(pretty_print=False, encoding=None, **kw)[source]

Converts a node with all of it’s children to a string.

Remaining arguments are passed to etree.tostring as is.

kwarg without_comments: bool because it works only in C14N flags: ‘pretty print’ and ‘encoding’ are ignored.

Parameters:
  • pretty_print (bool) – whether to format the output
  • encoding (str) – which encoding to use (ASCII by default)
Return type:

str

Returns:

node’s representation as a string

update(**kwargs)[source]

Updating or creation of new simple nodes.

Each dict key is used as a tagname and value as text.

xpath(path, namespaces=None, regexp=False, smart_strings=True, single_use=False)[source]

Executes XPath query on the lxml object and returns a correct object.

Parameters:
  • path (str) – XPath string e.g., ‘cars’/’car’
  • namespaces (str/dict) – e.g., ‘exslt’, ‘re’ or {'re': "http://exslt.org/regular-expressions"}
  • regexp (bool) – if True and no namespaces is provided, it will use exslt namespace
  • smart_strings (bool) –
  • single_use (bool) – faster method for using only once. Does not create XPathEvaluator instance.
>>> root = mappet.Mappet("<root><a>aB</a><b>aBc</b></root>")
>>> root.XPath(
    "//*[re:test(., '^abc$', 'i')]",
    namespaces='exslt',
    regexp=True,
)
xpath_evaluator(namespaces=None, regexp=False, smart_strings=True)[source]

Creates an XPathEvaluator instance for an ElementTree or an Element.

Returns:XPathEvaluator instance

mappet.mappet module

Module for dynamic mapping of XML trees to Python objects.

class mappet.mappet.Literal(xml)[source]

Bases: mappet.mappet.Node

Represents a leaf in an XML tree.

get(default=None, callback=None)[source]

Returns leaf’s value.

class mappet.mappet.Mappet(xml)[source]

Bases: mappet.mappet.Node

A node that may have children.

assign_dict(node, xml_dict)[source]

Assigns a Python dict to a lxml node.

Parameters:
  • node – A node to assign the dict to.
  • xml_dict – The dict with attributes/children to use.
static assign_literal(element, value)[source]

Assigns a literal.

If a given node doesn’t exist, it will be created.

Parameters:
  • element (etree.Element) – element to which we assign.
  • value – the value to assign
static assign_sequence_or_set(element, value)[source]
children(key=None)[source]

Returns node’s children.

Parameters:key – A key for filtering children by tagname.
create(tag, value)[source]

Creates a node, if it doesn’t exist yet.

Unlike attribute access, this allows to pass a node’s name with hyphens. Those hyphens will be normalized automatically.

In case the required element already exists, raises an exception. Updating/overwriting should be done using update`.

has_children()[source]

Returns true if a node has children.

iter_children(key=None)[source]

Iterates over children.

Parameters:key – A key for filtering children by tagname.
keys()[source]

Returns a set of node’s keys.

set(name, value)[source]

Assigns a new XML structure to the node.

A literal value, dict or list can be passed in. Works for all nested levels.

Dictionary: >>> m = Mappet(‘<root/>’) >>> m.head = {‘a’: ‘A’, ‘b’: {‘#text’: ‘B’, '@attr‘: ‘val’}} >>> m.head.to_str() ‘<head><a>A</a><b attr=”val”>B</b></head>’

List: >>> m.head = [{‘a’: i} for i in ‘ABC’] >>> m.head.to_str() ‘<head><a>A</a><a>B</a><a>C</a></head>’

Literals: >>> m.head.leaf = ‘A’ >>> m.head.leaf.get() ‘A’

sget(path, default=NONE_NODE)[source]

Enables access to nodes if one or more of them don’t exist.

Example: >>> m = Mappet(‘<root><tag attr1=”attr text”>text value</tag></root>’) >>> m.sget(‘tag’) text value >>> m.sget(‘tag.@attr1’) ‘attr text’ >>> m.sget(‘tag.#text’) ‘text value’ >>> m.sget(‘reply.vms_model_cars.car.0.params.doors’) NONE_NODE

Accessing nonexistent path returns None-like object with mocked converting functions which returns None: >>> m.sget(‘reply.fake_node’).to_dict() is None True

to_dict(**kw)[source]

Converts the lxml object to a dict.

possible kwargs:
without_comments: bool
to_str(pretty_print=False, encoding=None, **kw)[source]

Converts a node with all of it’s children to a string.

Remaining arguments are passed to etree.tostring as is.

kwarg without_comments: bool because it works only in C14N flags: ‘pretty print’ and ‘encoding’ are ignored.

Parameters:
  • pretty_print (bool) – whether to format the output
  • encoding (str) – which encoding to use (ASCII by default)
Return type:

str

Returns:

node’s representation as a string

update(**kwargs)[source]

Updating or creation of new simple nodes.

Each dict key is used as a tagname and value as text.

xpath(path, namespaces=None, regexp=False, smart_strings=True, single_use=False)[source]

Executes XPath query on the lxml object and returns a correct object.

Parameters:
  • path (str) – XPath string e.g., ‘cars’/’car’
  • namespaces (str/dict) – e.g., ‘exslt’, ‘re’ or {'re': "http://exslt.org/regular-expressions"}
  • regexp (bool) – if True and no namespaces is provided, it will use exslt namespace
  • smart_strings (bool) –
  • single_use (bool) – faster method for using only once. Does not create XPathEvaluator instance.
>>> root = mappet.Mappet("<root><a>aB</a><b>aBc</b></root>")
>>> root.XPath(
    "//*[re:test(., '^abc$', 'i')]",
    namespaces='exslt',
    regexp=True,
)
xpath_evaluator(namespaces=None, regexp=False, smart_strings=True)[source]

Creates an XPathEvaluator instance for an ElementTree or an Element.

Returns:XPathEvaluator instance
class mappet.mappet.Node(xml)[source]

Bases: object

Base class representing an XML node.

getattr(key, default=None, callback=None)[source]

Getting the attribute of an element.

>>> xml = etree.Element('root')
>>> xml.text = 'text'
>>> Node(xml).getattr('text')
'text'
>>> Node(xml).getattr('text', callback=str.upper)
'TEXT'
>>> Node(xml).getattr('wrong_attr', default='default')
'default'
static is_key_attr_or_text(key)[source]
setattr(key, value)[source]

Sets an attribute on a node.

>>> xml = etree.Element('root')
>>> Node(xml).setattr('text', 'text2')
>>> Node(xml).getattr('text')
'text2'
>>> Node(xml).setattr('attr', 'val')
>>> Node(xml).getattr('attr')
'val'
tag

Returns node’s tag name.

mappet.helpers module

Helper functions.

mappet.helpers.to_bool(value)[source]

Converts human boolean-like values to Python boolean.

Falls back to bool when value is not recognized.

Parameters:value – the value to convert
Returns:True if value is truthy, False otherwise
Return type:bool
mappet.helpers.to_date(value)[source]
mappet.helpers.to_datetime(value)[source]
mappet.helpers.to_decimal(value)[source]
mappet.helpers.to_float(value)[source]
mappet.helpers.to_int(value)[source]
mappet.helpers.to_str(value)[source]

Represents values as unicode strings to support diacritics.

mappet.helpers.to_time(value)[source]
mappet.helpers.from_bool(value)[source]
mappet.helpers.from_date(value)[source]
mappet.helpers.from_datetime(value)[source]
mappet.helpers.from_time(value)[source]
mappet.helpers.normalize_tag(tag)[source]

Normalizes tag name.

Parameters:tag (str) – tag name to normalize
Return type:str
Returns:normalized tag name
>>> normalize_tag('tag-NaMe')
'tag_name'
mappet.helpers.etree_to_dict(t, trim=True, **kw)[source]

Converts an lxml.etree object to Python dict.

>>> etree_to_dict(etree.Element('root'))
{'root': None}
Parameters:t (etree.Element) – lxml tree to convert
Returns d:a dict representing the lxml tree t
Return type:dict
mappet.helpers.dict_to_etree(d, root)[source]

Converts a dict to lxml.etree object.

>>> dict_to_etree({'root': {'#text': 'node_text', '@attr': 'val'}}, etree.Element('root')) 
<Element root at 0x...>
Parameters:
  • d (dict) – dict representing the XML tree
  • root (etree.Element) – XML node which will be assigned the resulting tree
Returns:

Textual representation of the XML tree

Return type:

str