Merge pull request #254 from barreverte/develop

tostring.escape : optimization
This commit is contained in:
Lance Stout 2013-09-12 10:21:56 -07:00
commit 23750357e2
3 changed files with 10 additions and 30 deletions

1
.gitignore vendored
View file

@ -12,3 +12,4 @@ sleekxmpp.egg-info/
*~ *~
.baboon/ .baboon/
.DS_STORE .DS_STORE
*.iml

View file

@ -16,6 +16,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import sys import sys
from xml.etree.ElementTree import _escape_cdata, _escape_attrib
if sys.version_info < (3, 0): if sys.version_info < (3, 0):
import types import types
@ -140,33 +141,12 @@ def tostring(xml=None, xmlns='', stream=None, outbuffer='',
def escape(text, use_cdata=False): def escape(text, use_cdata=False):
"""Convert special characters in XML to escape sequences. encoding = 'utf-8'
:param string text: The XML text to convert. if use_cdata:
:rtype: Unicode string return _escape_cdata(text, encoding)
"""
if sys.version_info < (3, 0):
if type(text) != types.UnicodeType:
text = unicode(text, 'utf-8', 'ignore')
escapes = {'&': '&amp;', text = _escape_attrib(text, encoding)
'<': '&lt;', if "'" in text:
'>': '&gt;', text = text.replace("'", "&apos;")
"'": '&apos;', return text
'"': '&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

View file

@ -34,8 +34,7 @@ class TestToString(SleekTest):
desired = """&lt;foo bar=&quot;baz&quot;&gt;&apos;Hi""" desired = """&lt;foo bar=&quot;baz&quot;&gt;&apos;Hi"""
desired += """ &amp; welcome!&apos;&lt;/foo&gt;""" desired += """ &amp; welcome!&apos;&lt;/foo&gt;"""
self.failUnless(escaped == desired, self.assertEqual(escaped, desired)
"XML escaping did not work: %s." % escaped)
def testEmptyElement(self): def testEmptyElement(self):
"""Test converting an empty element to a string.""" """Test converting an empty element to a string."""