Coverage for gws-app / gws / lib / xmlx / util.py: 93%

27 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-03-03 10:12 +0100

1import gws.lib.datetimex as dtx 

2 

3 

4def atom_to_string(s) -> tuple[str, bool]: 

5 """Return a string representation of a primitive value. 

6 

7 Returns: 

8 A tuple containing the string representation and a boolean indicating if the conversion was successful. 

9 """ 

10 

11 if s is None: 

12 return '', True 

13 

14 if isinstance(s, str): 

15 return s, True 

16 

17 if isinstance(s, (int, float, bool)): 

18 return str(s).lower(), True 

19 

20 if isinstance(s, dtx.dt.datetime): 

21 return dtx.to_iso_string(s, with_tz=':'), True 

22 

23 if isinstance(s, dtx.dt.date): 

24 return dtx.to_iso_date_string(s), True 

25 

26 return '', False 

27 

28 

29def escape_text(s: str) -> str: 

30 """Escape special characters in a string for XML.""" 

31 

32 s = s.replace('&', '&') 

33 s = s.replace('>', '>') 

34 s = s.replace('<', '&lt;') 

35 return s 

36 

37 

38def escape_attribute(s: str) -> str: 

39 """Escape special characters in a string for XML attributes.""" 

40 

41 s = s.replace('&', '&amp;') 

42 s = s.replace('"', '&quot;') 

43 s = s.replace('>', '&gt;') 

44 s = s.replace('<', '&lt;') 

45 s = s.replace('\t', '&#x9;') 

46 s = s.replace('\r', '&#xd;') 

47 s = s.replace('\n', '&#xa;') 

48 return s