Popular recipes by David Goodger http://code.activestate.com/recipes/users/1767132/2004-09-08T13:57:04-07:00ActiveState Code RecipesEncoding Unicode data for XML and HTML (Python) 2004-09-08T13:57:04-07:00David Goodgerhttp://code.activestate.com/recipes/users/1767132/http://code.activestate.com/recipes/303668-encoding-unicode-data-for-xml-and-html/ <p style="color: grey"> Python recipe 303668 by <a href="/recipes/users/1767132/">David Goodger</a> (<a href="/recipes/tags/text/">text</a>). Revision 2. </p> <p>The "xmlcharrefreplace" encoding error handler was introduced in Python 2.3. It is very useful when encoding Unicode data for HTML and other XML applications with limited (but popular) encodings like ASCII or ISO-Latin-1. 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.</p> <p>An HTML demonstration is included. Put the code into a file, run it with Python, and redirect the output to a .html file. Open the output file in a browser to see the results.</p> <p>A variation of this code is used in the Docutils project. The original idea for backporting "xmlcharrefreplace" to pre-2.3 Python was from Felix Wiemann.</p>