Something like this?

>>> from xml.sax.saxutils import escape
>>> escape("< & >")   
'&lt; &amp; &gt;'
Answer from mbarkhau on Stack Overflow
🌐
Python
wiki.python.org › moin › EscapingXml
Escaping XML - Python Wiki
November 15, 2008 - If we want character references to be considered, we can use the Expat XML parser included with all recent versions of Python. This function will do the trick: 1 import xml.parsers.expat 2 3 def unescape(s): 4 want_unicode = False 5 if isinstance(s, unicode): 6 s = s.encode("utf-8") 7 want_unicode = True 8 9 # the rest of this assumes that `s` is UTF-8 10 list = [] 11 12 # create and initialize a parser object 13 p = xml.parsers.expat.ParserCreate("utf-8") 14 p.buffer_text = True 15 p.returns_unicode = want_unicode 16 p.CharacterDataHandler = list.append 17 18 # parse the data wrapped in a dummy element 19 # (needed so the "document" is well-formed) 20 p.Parse("<e>", 0) 21 p.Parse(s, 0) 22 p.Parse("</e>", 1) 23 24 # join the extracted strings and return 25 es = "" 26 if want_unicode: 27 es = u"" 28 return es.join(list)
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding [1] is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring ...
🌐
Stuffaboutcode
stuffaboutcode.com › 2012 › 06 › python-encode-xml-escape-characters.html
<Stuff about="code" />: Python - encode XML escape characters
# encode xml escape characters def encodeXMLText(text): text = text.replace("&", "&amp;") text = text.replace("\"", "&quot;") text = text.replace("'", "&apos;") text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") return text
🌐
Python
docs.python.org › 3 › library › xml.sax.utils.html
xml.sax.saxutils — SAX Utilities
In other words, using an XMLGenerator as the content handler will reproduce the original document being parsed. out should be a file-like object which will default to sys.stdout. encoding is the encoding of the output stream which defaults to 'iso-8859-1'. short_empty_elements controls the formatting of elements that contain no content: if False (the default) they are emitted as a pair of start/end tags, if set to True they are emitted as a single self-closed tag.
🌐
GitHub
gist.github.com › walkermatt › 440b2c1ad444e9fa7fd0aebdc6d44cad
Reading and writing a UTF-8 encoded XML file with Python ElementTree · GitHub
Writing involves writing the XML doc to UTF8 encoded bytes by calling ElementTree.tostring and specifying encoding="utf-8", then open the destination for writing in UTF8 and write the decoded bytes.
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch12s11.html
Autodetecting XML Encoding - Python Cookbook [Book]
July 19, 2002 - Note that encoding_name might not have an installed decoder (e.g., EBCDIC) """ # A more efficient implementation would not decode the whole # buffer at once, but then we'd have to decode a character at # a time looking for the quote character, and that's a pain encoding = "utf_8" # According to the XML spec, this is the default # This code successively tries to refine the default: # Whenever it fails to refine, it falls back to # the last place encoding ...
Authors   Alex MartelliDavid Ascher
Published   2002
Pages   608
🌐
XML.com
xml.com › pub › a › 2002 › 11 › 13 › py-xml.html
Proper XML Output in Python
November 13, 2002 - Consider one of the earlier examples, with a slight change -- the word "degrees" has been replaced with the byte B0 (octal 260), which is the degree symbol in the popular ISO-8859-1 and Windows-1252 character encodings: $ python -i listing2.py >>> write_xml_cdata_log_entry(2, "In any triangle, each interior angle < 90\260") <entry level="ERROR" date="Tue Oct 22 06:33:51 2002"> In any triangle, each interior angle &lt; 90° </entry> >>>
Find elsewhere
🌐
ActiveState
code.activestate.com › recipes › 303668-encoding-unicode-data-for-xml-and-html
Encoding Unicode data for XML and HTML « Python recipes « ActiveState Code
September 7, 2004 - The following code contains a trivial function "encode_for_xml" that illustrates the "xmlcharrefreplace" error handler, and a function "_xmlcharref_encode" which emulates "xmlcharrefreplace" for Python pre-2.3.
🌐
Virtualzero
blog.virtualzero.tech › entries › python › xml › how-to-encode-strings-for-xml-with-python
How to Encode Strings for XML with Python | VirtualZero Blog
March 22, 2020 - Stings within XML tags need to be properly formatted. Without proper formatting, a XML Parsing Error is likely to occur. This tutorial demonstrates how to encode strings properly for XML using Python.
🌐
W3Schools
w3schools.com › python › ref_string_encode.asp
Python String encode() Method
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
🌐
Python
docs.python.org › 3.2 › library › xml.etree.elementtree.html
19.6. xml.etree.ElementTree — The ElementTree XML API — Python v3.2.6 documentation
October 12, 2014 - Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding [1] is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string. method is either "xml", "html" or "text" (default is "xml").
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › scenarios › xml
XML parsing — The Hitchhiker's Guide to Python
from xmlschema import XMLSchema, etree_tostring # load a XSD schema file schema = XMLSchema("your_schema.xsd") # validate against the schema schema.validate("your_file.xml") # or schema.is_valid("your_file.xml") # decode a file data = schmema.decode("your_file.xml") # encode to string s = etree_tostring(schema.encode(data)) This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
🌐
GitHub
gist.github.com › 3067859
Different variants of writting XML in Python · GitHub
Different variants of writting XML in Python · Raw · writexml.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.