An XML text object used to represent text content. @ivar lang: The (optional) language flag. @type lang: bool @ivar escaped: The (optional) XML special character escaped flag. @type escaped: bool
| 22 | |
| 23 | |
| 24 | class Text(str): |
| 25 | """ |
| 26 | An XML text object used to represent text content. |
| 27 | @ivar lang: The (optional) language flag. |
| 28 | @type lang: bool |
| 29 | @ivar escaped: The (optional) XML special character escaped flag. |
| 30 | @type escaped: bool |
| 31 | """ |
| 32 | __slots__ = ('lang', 'escaped',) |
| 33 | |
| 34 | @classmethod |
| 35 | def __valid(cls, *args): |
| 36 | return len(args) and args[0] is not None |
| 37 | |
| 38 | def __new__(cls, *args, **kwargs): |
| 39 | if cls.__valid(*args): |
| 40 | lang = kwargs.pop('lang', None) |
| 41 | escaped = kwargs.pop('escaped', False) |
| 42 | result = super(Text, cls).__new__(cls, *args, **kwargs) |
| 43 | result.lang = lang |
| 44 | result.escaped = escaped |
| 45 | else: |
| 46 | result = None |
| 47 | return result |
| 48 | |
| 49 | def escape(self): |
| 50 | """ |
| 51 | Encode (escape) special XML characters. |
| 52 | @return: The text with XML special characters escaped. |
| 53 | @rtype: L{Text} |
| 54 | """ |
| 55 | if not self.escaped: |
| 56 | post = sax.encoder.encode(self) |
| 57 | escaped = post != self |
| 58 | return Text(post, lang=self.lang, escaped=escaped) |
| 59 | return self |
| 60 | |
| 61 | def unescape(self): |
| 62 | """ |
| 63 | Decode (unescape) special XML characters. |
| 64 | @return: The text with escaped XML special characters decoded. |
| 65 | @rtype: L{Text} |
| 66 | """ |
| 67 | if self.escaped: |
| 68 | post = sax.encoder.decode(self) |
| 69 | return Text(post, lang=self.lang) |
| 70 | return self |
| 71 | |
| 72 | def trim(self): |
| 73 | post = self.strip() |
| 74 | return Text(post, lang=self.lang, escaped=self.escaped) |
| 75 | |
| 76 | def __add__(self, other): |
| 77 | joined = u''.join((self, other)) |
| 78 | result = Text(joined, lang=self.lang, escaped=self.escaped) |
| 79 | if isinstance(other, Text): |
| 80 | result.escaped = self.escaped or other.escaped |
| 81 | return result |
no outgoing calls
no test coverage detected