2014-07-17 12:19:04 +00:00
|
|
|
.. module:: slixmpp.xmlstream.tostring
|
2011-11-22 23:25:02 +00:00
|
|
|
|
|
|
|
.. _tostring:
|
|
|
|
|
|
|
|
XML Serialization
|
2011-11-23 00:25:33 +00:00
|
|
|
=================
|
|
|
|
|
2014-07-17 12:19:04 +00:00
|
|
|
Since the XML layer of Slixmpp is based on :mod:`~xml.etree.ElementTree`,
|
2011-11-23 00:25:33 +00:00
|
|
|
why not just use the built-in :func:`~xml.etree.ElementTree.tostring`
|
|
|
|
method? The answer is that using that method produces ugly results when
|
|
|
|
using namespaces. The :func:`tostring()` method used here intelligently
|
|
|
|
hides namespaces when able and does not introduce excessive namespace
|
|
|
|
prefixes::
|
|
|
|
|
2014-07-17 12:19:04 +00:00
|
|
|
>>> from slixmpp.xmlstream.tostring import tostring
|
2011-11-23 00:25:33 +00:00
|
|
|
>>> from xml.etree import cElementTree 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 :func:`tostring()` may
|
|
|
|
produce unexpected results depending on how the :func:`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
|
2014-07-17 12:19:04 +00:00
|
|
|
you create a :class:`~slixmpp.stanza.message.Message` instance and dump
|
2011-11-23 00:25:33 +00:00
|
|
|
it to the terminal, the ``jabber:client`` namespace will appear.
|
2011-11-22 23:25:02 +00:00
|
|
|
|
2015-02-24 17:58:40 +00:00
|
|
|
.. autofunction:: slixmpp.xmlstream.tostring
|
2011-11-22 23:25:02 +00:00
|
|
|
|
|
|
|
Escaping Special Characters
|
|
|
|
---------------------------
|
|
|
|
|
2011-11-23 00:25:33 +00:00
|
|
|
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: ``&``, ``<``, ``>``, ``'``, and ``"``.
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
2015-02-24 17:58:40 +00:00
|
|
|
..
|
|
|
|
autofunction:: xml_escape
|