Ram Rachum Ram Rachum - 1 year ago 131
Python Question

Python: Escaping strings for use in XML

I'm using Python's

to create an XML document. (Logical structure -> XML string, not the other way around.)

How do I make it escape the strings I provide so they won't be able to mess up the XML?

Answer Source

Do you mean you do something like this:

from xml.dom.minidom import Text, Element

t = Text()
e = Element('p')

t.data = '<bar><a/><baz spam="eggs"> & blabla &entity;</>'

Then you will get nicely escaped XML string:

>>> e.toxml()
'<p>&lt;bar&gt;&lt;a/&gt;&lt;baz spam=&quot;eggs&quot;&gt; &amp; blabla &amp;entity;&lt;/&gt;</p>'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download