Question :
Escaping strings for use in XML
I’m using Python’s xml.dom.minidom
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 #1:
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;</>'
e.appendChild(t)
Then you will get nicely escaped XML string:
>>> e.toxml()
'<p><bar><a/><baz spam="eggs"> & blabla &entity;</></p>'
Answer #2:
Something like this?
>>> from xml.sax.saxutils import escape
>>> escape("< & >")
'< & >'
Answer #3:
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(""", ""&
quot
)