An XML special character encoder/decoder. @cvar encodings: A mapping of special characters encoding. @type encodings: [(str,str)] @cvar decodings: A mapping of special characters decoding. @type decodings: [(str,str)] @cvar special: A list of special characters @type spe
| 22 | |
| 23 | |
| 24 | class Encoder: |
| 25 | """ |
| 26 | An XML special character encoder/decoder. |
| 27 | @cvar encodings: A mapping of special characters encoding. |
| 28 | @type encodings: [(str,str)] |
| 29 | @cvar decodings: A mapping of special characters decoding. |
| 30 | @type decodings: [(str,str)] |
| 31 | @cvar special: A list of special characters |
| 32 | @type special: [char] |
| 33 | """ |
| 34 | |
| 35 | encodings = ( |
| 36 | ('&', '&'), |
| 37 | ('<', '<'), |
| 38 | ('>', '>'), |
| 39 | ('"', '"'), |
| 40 | ("'", ''') |
| 41 | ) |
| 42 | decodings = ( |
| 43 | ('<', '<'), |
| 44 | ('>', '>'), |
| 45 | ('"', '"'), |
| 46 | (''', "'"), |
| 47 | ('&', '&') |
| 48 | ) |
| 49 | special = ('&', '<', '>', '"', "'") |
| 50 | |
| 51 | def needsEncoding(self, s): |
| 52 | """ |
| 53 | Get whether string I{s} contains special characters. |
| 54 | @param s: A string to check. |
| 55 | @type s: str |
| 56 | @return: True if needs encoding. |
| 57 | @rtype: boolean |
| 58 | """ |
| 59 | if isinstance(s, str): |
| 60 | for c in self.special: |
| 61 | if c in s: |
| 62 | return True |
| 63 | return False |
| 64 | |
| 65 | def encode(self, s): |
| 66 | """ |
| 67 | Encode special characters found in string I{s}. |
| 68 | @param s: A string to encode. |
| 69 | @type s: str |
| 70 | @return: The encoded string. |
| 71 | @rtype: str |
| 72 | """ |
| 73 | if isinstance(s, str) and self.needsEncoding(s): |
| 74 | for x in self.encodings: |
| 75 | s = re.sub(x[0], x[1], s) |
| 76 | return s |
| 77 | |
| 78 | def decode(self, s): |
| 79 | """ |
| 80 | Decode special characters encodings found in string I{s}. |
| 81 | @param s: A string to decode. |