Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 956
Ram Rachum Avatar asked Oct 10 '09 00:10

Ram Rachum


People also ask

How do I escape a string in XML?

XML escape characters There are only five: " &quot; ' &apos; < &lt; > &gt; & &amp; Escaping characters depends on where the special character is used. The examples can be validated at the W3C Markup Validation Service.

Does apostrophe need to be escaped in XML?

If the delimiter for the attribute value is the apostrophe, then the quote character is legal but the apostrophe character is not, because it would signal the end of the attribute value. If an apostrophe is needed, the character entity &apos; must be used.


2 Answers

Something like this?

>>> from xml.sax.saxutils import escape >>> escape("< & >")    '&lt; &amp; &gt;' 
like image 183
mbarkhau Avatar answered Sep 19 '22 12:09

mbarkhau


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

So here is another one:

def escape( str ):     str = str.replace("&", "&amp;")     str = str.replace("<", "&lt;")     str = str.replace(">", "&gt;")     str = str.replace("\"", "&quot;")     return str 

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

like image 41
MichaelMoser Avatar answered Sep 19 '22 12:09

MichaelMoser