1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 """
18 Provides XML I{special character} encoder classes.
19 """
20
21 import re
22
24 """
25 An XML special character encoder/decoder.
26 @cvar encodings: A mapping of special characters encoding.
27 @type encodings: [(str,str)]
28 @cvar decodings: A mapping of special characters decoding.
29 @type decodings: [(str,str)]
30 @cvar special: A list of special characters
31 @type special: [char]
32 """
33
34 encodings = \
35 (( '&(?!(amp|lt|gt|quot|apos);)', '&' ),( '<', '<' ),( '>', '>' ),( '"', '"' ),("'", ''' ))
36 decodings = \
37 (( '<', '<' ),( '>', '>' ),( '"', '"' ),( ''', "'" ),( '&', '&' ))
38 special = \
39 ('&', '<', '>', '"', "'")
40
42 """
43 Get whether string I{s} contains special characters.
44 @param s: A string to check.
45 @type s: str
46 @return: True if needs encoding.
47 @rtype: boolean
48 """
49 if isinstance(s, basestring):
50 for c in self.special:
51 if c in s:
52 return True
53 return False
54
56 """
57 Encode special characters found in string I{s}.
58 @param s: A string to encode.
59 @type s: str
60 @return: The encoded string.
61 @rtype: str
62 """
63 if isinstance(s, basestring) and self.needsEncoding(s):
64 for x in self.encodings:
65 s = re.sub(x[0], x[1], s)
66 return s
67
69 """
70 Decode special characters encodings found in string I{s}.
71 @param s: A string to decode.
72 @type s: str
73 @return: The decoded string.
74 @rtype: str
75 """
76 if isinstance(s, basestring) and '&' in s:
77 for x in self.decodings:
78 s = s.replace(x[0], x[1])
79 return s
80