summaryrefslogtreecommitdiff
path: root/sleekxmpp/xmlstream
diff options
context:
space:
mode:
authorJean-Philippe Caruana <jp@barreverte.fr>2013-07-30 18:51:23 +0200
committerJean-Philippe Caruana <jp@barreverte.fr>2013-07-30 18:51:23 +0200
commitc02adbb8e1a272196f891e3487e5ce079868cb0d (patch)
tree38b3042f50d5ff082e9418857638cc8503ab230b /sleekxmpp/xmlstream
parent88e64dbfae71b4518459b7997c0a6e70d2e48e11 (diff)
downloadslixmpp-c02adbb8e1a272196f891e3487e5ce079868cb0d.tar.gz
slixmpp-c02adbb8e1a272196f891e3487e5ce079868cb0d.tar.bz2
slixmpp-c02adbb8e1a272196f891e3487e5ce079868cb0d.tar.xz
slixmpp-c02adbb8e1a272196f891e3487e5ce079868cb0d.zip
tostring.escape : optimization
use of xml.etree.ElementTree._escape_attrib and xml.etree.ElementTree._escape_cdata
Diffstat (limited to 'sleekxmpp/xmlstream')
-rw-r--r--sleekxmpp/xmlstream/tostring.py53
1 files changed, 23 insertions, 30 deletions
diff --git a/sleekxmpp/xmlstream/tostring.py b/sleekxmpp/xmlstream/tostring.py
index c49abd3e..771f8dab 100644
--- a/sleekxmpp/xmlstream/tostring.py
+++ b/sleekxmpp/xmlstream/tostring.py
@@ -140,33 +140,26 @@ def tostring(xml=None, xmlns='', stream=None, outbuffer='',
def escape(text, use_cdata=False):
- """Convert special characters in XML to escape sequences.
-
- :param string text: The XML text to convert.
- :rtype: Unicode string
- """
- if sys.version_info < (3, 0):
- if type(text) != types.UnicodeType:
- text = unicode(text, 'utf-8', 'ignore')
-
- escapes = {'&': '&amp;',
- '<': '&lt;',
- '>': '&gt;',
- "'": '&apos;',
- '"': '&quot;'}
-
- if not use_cdata:
- text = list(text)
- for i, c in enumerate(text):
- text[i] = escapes.get(c, c)
- return ''.join(text)
- else:
- escape_needed = False
- for c in text:
- if c in escapes:
- escape_needed = True
- break
- if escape_needed:
- escaped = map(lambda x : "<![CDATA[%s]]>" % x, text.split("]]>"))
- return "<![CDATA[]]]><![CDATA[]>]]>".join(escaped)
- return text
+ encoding = 'utf-8'
+ from xml.etree.ElementTree import _escape_cdata, _raise_serialization_error
+
+ if use_cdata:
+ return _escape_cdata(text, encoding)
+
+ # copied from xml.etree.ElementTree._escape_attrib with "&apos;" case
+ try:
+ if "&" in text:
+ text = text.replace("&", "&amp;")
+ if "<" in text:
+ text = text.replace("<", "&lt;")
+ if ">" in text:
+ text = text.replace(">", "&gt;")
+ if "\"" in text:
+ text = text.replace("\"", "&quot;")
+ if "'" in text:
+ text = text.replace("'", "&apos;")
+ if "\n" in text:
+ text = text.replace("\n", "&#10;")
+ return text.encode(encoding, "xmlcharrefreplace")
+ except (TypeError, AttributeError):
+ _raise_serialization_error(text)