tostring.escape : optimization
use of xml.etree.ElementTree._escape_attrib and xml.etree.ElementTree._escape_cdata
This commit is contained in:
parent
88e64dbfae
commit
c02adbb8e1
@ -140,33 +140,26 @@ 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'
|
||||||
|
from xml.etree.ElementTree import _escape_cdata, _raise_serialization_error
|
||||||
|
|
||||||
: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 = {'&': '&',
|
# copied from xml.etree.ElementTree._escape_attrib with "'" case
|
||||||
'<': '<',
|
try:
|
||||||
'>': '>',
|
if "&" in text:
|
||||||
"'": ''',
|
text = text.replace("&", "&")
|
||||||
'"': '"'}
|
if "<" in text:
|
||||||
|
text = text.replace("<", "<")
|
||||||
if not use_cdata:
|
if ">" in text:
|
||||||
text = list(text)
|
text = text.replace(">", ">")
|
||||||
for i, c in enumerate(text):
|
if "\"" in text:
|
||||||
text[i] = escapes.get(c, c)
|
text = text.replace("\"", """)
|
||||||
return ''.join(text)
|
if "'" in text:
|
||||||
else:
|
text = text.replace("'", "'")
|
||||||
escape_needed = False
|
if "\n" in text:
|
||||||
for c in text:
|
text = text.replace("\n", " ")
|
||||||
if c in escapes:
|
return text.encode(encoding, "xmlcharrefreplace")
|
||||||
escape_needed = True
|
except (TypeError, AttributeError):
|
||||||
break
|
_raise_serialization_error(text)
|
||||||
if escape_needed:
|
|
||||||
escaped = map(lambda x : "<![CDATA[%s]]>" % x, text.split("]]>"))
|
|
||||||
return "<![CDATA[]]]><![CDATA[]>]]>".join(escaped)
|
|
||||||
return text
|
|
||||||
|
@ -34,8 +34,7 @@ class TestToString(SleekTest):
|
|||||||
desired = """<foo bar="baz">'Hi"""
|
desired = """<foo bar="baz">'Hi"""
|
||||||
desired += """ & welcome!'</foo>"""
|
desired += """ & welcome!'</foo>"""
|
||||||
|
|
||||||
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."""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user