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
« prev ^ index » next coverage.py v7.16.2, created at 2026-10-05 13:35 +0200
1"""Helper for custom XML namespaces.
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``.
8By default, a custom namespace is declared to extend the GML3 schema.
10Example::
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 }
21Example::
23 helper = root.app.helper('xml')
24 ns = helper.add_namespace(gws.Config(xmlns='demo', uri='https://example.com/namespace/demo'))
25"""
27from typing import Optional
28import gws
29import gws.lib.xmlx
32class NamespaceConfig(gws.Config):
33 """Custom XML namespace for generated XML documents."""
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."""
47@gws.ext.config.helper('xml')
48class Config(gws.Config):
49 """Custom XML namespaces for generated XML documents."""
51 namespaces: list[NamespaceConfig]
52 """Custom namespaces to register."""
55@gws.ext.object.helper('xml')
56class Object(gws.Node):
57 """XML helper, which registers custom namespaces."""
59 def configure(self):
60 for c in self.cfg('namespaces', default=[]):
61 self.add_namespace(c)
63 def add_namespace(self, cfg: NamespaceConfig) -> gws.XmlNamespace:
64 """Create a custom namespace and register it globally.
66 Args:
67 cfg: Namespace configuration.
69 Returns:
70 The registered namespace.
72 Raises:
73 ``gws.ConfigurationError``: If the prefix or the URI conflicts with an already registered namespace.
74 """
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 )
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
91 return ns