XML Serialization

1.7 Documentation

«  XML Stream   ::   Contents   ::   Plugin index  »

XML Serialization

Since the XML layer of Slixmpp is based on ElementTree, why not just use the built-in tostring() method? The answer is that using that method produces ugly results when using namespaces. The tostring() method used here intelligently hides namespaces when able and does not introduce excessive namespace prefixes:

>>> from slixmpp.xmlstream.tostring import tostring
>>> from xml.etree import ElementTree as ET
>>> xml = ET.fromstring('<foo xmlns="bar"><baz /></foo>')
>>> ET.tostring(xml)
'<ns0:foo xmlns:ns0="bar"><ns0:baz /></foo>'
>>> tostring(xml)
'<foo xmlns="bar"><baz /></foo>'

As a side effect of this namespace hiding, using tostring() may produce unexpected results depending on how the tostring() method is invoked. For example, when sending XML on the wire, the main XMPP stanzas with their namespace of jabber:client will not include the namespace because that is already declared by the stream header. But, if you create a Message instance and dump it to the terminal, the jabber:client namespace will appear.

slixmpp.xmlstream.tostring(xml=None, xmlns='', stream=None, outbuffer='', top_level=False, open_only=False, namespaces=None)[source]

Serialize an XML object to a Unicode string.

If an outer xmlns is provided using xmlns, then the current element’s namespace will not be included if it matches the outer namespace. An exception is made for elements that have an attached stream, and appear at the stream root.

Parameters
  • xml (Element) – The XML object to serialize.

  • xmlns (string) – Optional namespace of an element wrapping the XML object.

  • stream (XMLStream) – The XML stream that generated the XML object.

  • outbuffer (string) – Optional buffer for storing serializations during recursive calls.

  • top_level (bool) – Indicates that the element is the outermost element.

  • namespaces (set) – Track which namespaces are in active use so that new ones can be declared when needed.

Return type

Unicode string

Escaping Special Characters

In order to prevent errors when sending arbitrary text as the textual content of an XML element, certain characters must be escaped. These are: &, <, >, ", and '. The default escaping mechanism is to replace those characters with their equivalent escape entities: &amp;, &lt;, &gt;, &apos;, and &quot;.

In the future, the use of CDATA sections may be allowed to reduce the size of escaped text or for when other XMPP processing agents do not undertand these entities.

«  XML Stream   ::   Contents   ::   Plugin index  »