Escaping strings for use in XML Escaping strings for use in XML xml xml

Escaping strings for use in XML


Something like this?

>>> from xml.sax.saxutils import escape>>> escape("< & >")   '< & >'


xml.sax.saxutils does not escape quotation characters (")

So here is another one:

def escape( str ):    str = str.replace("&", "&")    str = str.replace("<", "<")    str = str.replace(">", ">")    str = str.replace("\"", """)    return str

if you look it up then xml.sax.saxutils only does string replace


xml.sax.saxutils.escape only escapes &, <, and > by default, but it does provide an entities parameter to additionally escape other strings:

from xml.sax.saxutils import escapedef xmlescape(data):    return escape(data, entities={        "'": "&apos;",        "\"": """    })

xml.sax.saxutils.escape uses str.replace() internally, so you can also skip the import and write your own function, as shown in MichealMoser's answer.