Coverage for gws-app/gws/plugin/xml_helper/__init__.py: 90%

29 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-05 13:35 +0200

1"""Helper for custom XML namespaces. 

2 

3The helper registers custom XML namespaces, which can then be used in 

4generated XML documents. The namespaces are configured in the ``namespaces`` list and 

5registered globally in :obj:`gws.lib.xmlx.namespace` when the helper is 

6configured. Other code can add namespaces at run time with ``add_namespace``. 

7 

8By default, a custom namespace is declared to extend the GML3 schema. 

9 

10Example:: 

11 

12 helpers+ { 

13 type "xml" 

14 namespaces+ { 

15 xmlns "demo" 

16 uri "https://example.com/namespace/demo" 

17 schemaLocation "https://example.com/namespace/demo.xsd" 

18 } 

19 } 

20 

21Example:: 

22 

23 helper = root.app.helper('xml') 

24 ns = helper.add_namespace(gws.Config(xmlns='demo', uri='https://example.com/namespace/demo')) 

25""" 

26 

27from typing import Optional 

28import gws 

29import gws.lib.xmlx 

30 

31 

32class NamespaceConfig(gws.Config): 

33 """Custom XML namespace for generated XML documents.""" 

34 

35 xmlns: str 

36 """Default prefix for this namespace.""" 

37 uri: gws.Url 

38 """Namespace URI.""" 

39 schemaLocation: Optional[gws.Url] 

40 """URL of the namespace XML schema.""" 

41 version: str = '' 

42 """Ignored. (deprecated in 8.5)""" 

43 extendsGml: bool = True 

44 """Namespace schema extends the GML3 schema.""" 

45 

46 

47@gws.ext.config.helper('xml') 

48class Config(gws.Config): 

49 """Custom XML namespaces for generated XML documents.""" 

50 

51 namespaces: list[NamespaceConfig] 

52 """Custom namespaces to register.""" 

53 

54 

55@gws.ext.object.helper('xml') 

56class Object(gws.Node): 

57 """XML helper, which registers custom namespaces.""" 

58 

59 def configure(self): 

60 for c in self.cfg('namespaces', default=[]): 

61 self.add_namespace(c) 

62 

63 def add_namespace(self, cfg: NamespaceConfig) -> gws.XmlNamespace: 

64 """Create a custom namespace and register it globally. 

65 

66 Args: 

67 cfg: Namespace configuration. 

68 

69 Returns: 

70 The registered namespace. 

71 

72 Raises: 

73 ``gws.ConfigurationError``: If the prefix or the URI conflicts with an already registered namespace. 

74 """ 

75 

76 xmlns = cfg.get('xmlns') 

77 if cfg.get('version'): 

78 self.root.config_warning(f'"xml.namespaces.version" is deprecated and ignored (namespace {xmlns!r})') 

79 ns = gws.lib.xmlx.namespace.new( 

80 prefix=xmlns, 

81 uri=cfg.get('uri'), 

82 schemaLocation=cfg.get('schemaLocation') or '', 

83 extendsGml=cfg.get('extendsGml', True), 

84 ) 

85 

86 try: 

87 gws.lib.xmlx.namespace.register(ns) 

88 except gws.lib.xmlx.Error as exc: 

89 raise gws.ConfigurationError(str(exc)) from exc 

90 

91 return ns