urban-json-xml 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 black beard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-xml
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : lecture de fichiers XML (fonction de template loadxml).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,xml,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: Markup
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Requires-Dist: defusedxml>=0.7
27
+ Dynamic: license-file
28
+
29
+ # urban-json-xml
30
+
31
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : lecture de fichiers **XML**
32
+ dans les templates, via la fonction `loadxml`. Suit les conventions XML↔JSON du
33
+ `XmlNodeConverter` (.NET/Newtonsoft).
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install urban-json-xml # tire urban-json et defusedxml en dépendances
39
+ ```
40
+
41
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`) :
42
+ `loadxml` devient utilisable dans les templates.
43
+
44
+ ## Utilisation
45
+
46
+ ```python
47
+ from urban_json import JsltTemplate
48
+
49
+ # catalog.xml :
50
+ # <catalog>
51
+ # <book id="1"><title>A</title></book>
52
+ # <book id="2"><title>B</title></book>
53
+ # </catalog>
54
+ tpl = JsltTemplate.parse('[ { "$source": select(loadxml("catalog.xml"), $.catalog.book), "t": $.title } ]')
55
+ tpl.transform({})
56
+ # -> [{'t': 'A'}, {'t': 'B'}]
57
+ ```
58
+
59
+ `loadxml` renvoie un objet ; on navigue dedans avec `select`/`selectmany` (fonctions
60
+ du cœur) avant d'alimenter une boucle `$source`, un filtre `?(...)`, etc.
61
+
62
+ ## Conventions de conversion (Newtonsoft)
63
+
64
+ | XML | JSON |
65
+ |---|---|
66
+ | `<a>v</a>` | `{"a": "v"}` |
67
+ | `<a x="1">v</a>` | `{"a": {"@x": "1", "#text": "v"}}` |
68
+ | `<a/>` | `{"a": null}` |
69
+ | `<a><b>1</b><b>2</b></a>` | `{"a": {"b": ["1", "2"]}}` (frères homonymes → tableau) |
70
+
71
+ - Attributs → propriétés préfixées par `@`.
72
+ - Texte d'un élément mixte → clé `#text`.
73
+ - Les valeurs restent des **chaînes** (comme Newtonsoft, pas de coercition).
74
+
75
+ ## Signature
76
+
77
+ ```
78
+ loadxml(source_path, attribute_prefix="@", text_key="#text", strip_namespaces=true)
79
+ ```
80
+
81
+ | Paramètre | Rôle |
82
+ |---|---|
83
+ | `source_path` | chemin du fichier XML |
84
+ | `attribute_prefix` | préfixe des propriétés issues d'attributs (défaut `@`) |
85
+ | `text_key` | clé portant le texte d'un élément mixte (défaut `#text`) |
86
+ | `strip_namespaces` | réduit `{uri}local` au nom local (défaut `true`) |
87
+
88
+ ## Sécurité
89
+
90
+ Le XML est analysé avec [`defusedxml`](https://pypi.org/project/defusedxml/) :
91
+ entités externes et expansion d'entités désactivées (protection XXE /
92
+ « billion laughs »).
93
+
94
+ ## Licence
95
+
96
+ Apache-2.0.
@@ -0,0 +1,68 @@
1
+ # urban-json-xml
2
+
3
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : lecture de fichiers **XML**
4
+ dans les templates, via la fonction `loadxml`. Suit les conventions XML↔JSON du
5
+ `XmlNodeConverter` (.NET/Newtonsoft).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install urban-json-xml # tire urban-json et defusedxml en dépendances
11
+ ```
12
+
13
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`) :
14
+ `loadxml` devient utilisable dans les templates.
15
+
16
+ ## Utilisation
17
+
18
+ ```python
19
+ from urban_json import JsltTemplate
20
+
21
+ # catalog.xml :
22
+ # <catalog>
23
+ # <book id="1"><title>A</title></book>
24
+ # <book id="2"><title>B</title></book>
25
+ # </catalog>
26
+ tpl = JsltTemplate.parse('[ { "$source": select(loadxml("catalog.xml"), $.catalog.book), "t": $.title } ]')
27
+ tpl.transform({})
28
+ # -> [{'t': 'A'}, {'t': 'B'}]
29
+ ```
30
+
31
+ `loadxml` renvoie un objet ; on navigue dedans avec `select`/`selectmany` (fonctions
32
+ du cœur) avant d'alimenter une boucle `$source`, un filtre `?(...)`, etc.
33
+
34
+ ## Conventions de conversion (Newtonsoft)
35
+
36
+ | XML | JSON |
37
+ |---|---|
38
+ | `<a>v</a>` | `{"a": "v"}` |
39
+ | `<a x="1">v</a>` | `{"a": {"@x": "1", "#text": "v"}}` |
40
+ | `<a/>` | `{"a": null}` |
41
+ | `<a><b>1</b><b>2</b></a>` | `{"a": {"b": ["1", "2"]}}` (frères homonymes → tableau) |
42
+
43
+ - Attributs → propriétés préfixées par `@`.
44
+ - Texte d'un élément mixte → clé `#text`.
45
+ - Les valeurs restent des **chaînes** (comme Newtonsoft, pas de coercition).
46
+
47
+ ## Signature
48
+
49
+ ```
50
+ loadxml(source_path, attribute_prefix="@", text_key="#text", strip_namespaces=true)
51
+ ```
52
+
53
+ | Paramètre | Rôle |
54
+ |---|---|
55
+ | `source_path` | chemin du fichier XML |
56
+ | `attribute_prefix` | préfixe des propriétés issues d'attributs (défaut `@`) |
57
+ | `text_key` | clé portant le texte d'un élément mixte (défaut `#text`) |
58
+ | `strip_namespaces` | réduit `{uri}local` au nom local (défaut `true`) |
59
+
60
+ ## Sécurité
61
+
62
+ Le XML est analysé avec [`defusedxml`](https://pypi.org/project/defusedxml/) :
63
+ entités externes et expansion d'entités désactivées (protection XXE /
64
+ « billion laughs »).
65
+
66
+ ## Licence
67
+
68
+ Apache-2.0.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "urban-json-xml"
7
+ dynamic = ["version"]
8
+ description = "Plugin urban-json : lecture de fichiers XML (fonction de template loadxml)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Gael Beard", email = "gaelgael5@gmail.com" }]
14
+ keywords = ["json", "transform", "template", "jslt", "xml", "plugin"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Topic :: Text Processing :: Markup",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "urban-json",
31
+ "defusedxml>=0.7",
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/gaelgael5/Jslt"
36
+ Repository = "https://github.com/gaelgael5/Jslt"
37
+
38
+ # Découverte automatique par urban-json : installer ce paquet suffit à exposer `loadxml`.
39
+ [project.entry-points."urban_json.functions"]
40
+ xml = "urban_json_xml:register"
41
+
42
+ [tool.setuptools.dynamic]
43
+ version = { attr = "urban_json_xml.__version__" }
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
47
+
48
+ [tool.setuptools.package-data]
49
+ urban_json_xml = ["py.typed"]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ pythonpath = ["src"]
54
+
55
+ [tool.ruff]
56
+ line-length = 100
57
+ src = ["src", "tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,116 @@
1
+ """Plugin jslt : lecture de fichiers XML (``loadxml``).
2
+
3
+ Le moteur .NET n'expose pas de fonction de template ``loadxml`` mais convertit
4
+ XML ↔ JSON via le ``XmlNodeConverter`` (conventions Newtonsoft). Ce plugin porte
5
+ ces **mêmes conventions** sous forme d'une fonction ``loadxml`` :
6
+
7
+ * un élément devient un objet ;
8
+ * un attribut devient une propriété préfixée par ``@`` ;
9
+ * le texte d'un élément (s'il a aussi des attributs/enfants) va dans ``#text`` ;
10
+ un élément qui n'a que du texte prend directement cette valeur (chaîne) ;
11
+ * des éléments frères de même nom deviennent un tableau ;
12
+ * l'élément racine est enveloppé : ``<root>…</root>`` → ``{"root": {…}}``.
13
+
14
+ Les valeurs restent des **chaînes** (comme Newtonsoft : pas de coercition de type).
15
+
16
+ Sécurité : le XML est analysé avec ``defusedxml`` (entités externes et expansion
17
+ d'entités désactivées — protection XXE / « billion laughs »).
18
+
19
+ Découvert automatiquement par ``jslt`` via l'entry point ``urban_json.functions``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Any
25
+
26
+ from defusedxml.ElementTree import parse as _parse
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ __all__ = ["execute_loadxml", "register"]
31
+
32
+ # Clés spéciales, fidèles au XmlNodeConverter (.NET/Newtonsoft).
33
+ _TEXT_KEY = "#text"
34
+ _ATTR_PREFIX = "@"
35
+
36
+
37
+ def _local_name(tag: str, strip_namespaces: bool) -> str:
38
+ """Nom local d'une balise/attribut ``{uri}local`` -> ``local`` (si demandé)."""
39
+ if strip_namespaces and tag.startswith("{"):
40
+ return tag.rsplit("}", 1)[-1]
41
+ return tag
42
+
43
+
44
+ def _element_to_obj(
45
+ element: Any, attribute_prefix: str, text_key: str, strip_namespaces: bool
46
+ ) -> Any:
47
+ """Convertit un élément ElementTree en structure JSON (conventions Newtonsoft)."""
48
+ children = list(element)
49
+ attributes = element.attrib
50
+ text = (element.text or "").strip()
51
+
52
+ # Feuille sans attribut ni enfant : la valeur texte directe (ou None si vide).
53
+ if not children and not attributes:
54
+ return text if text else None
55
+
56
+ obj: dict[str, Any] = {}
57
+
58
+ for name, value in attributes.items():
59
+ obj[attribute_prefix + _local_name(name, strip_namespaces)] = value
60
+
61
+ # Regroupe les enfants par nom : les frères homonymes forment un tableau.
62
+ groups: dict[str, list[Any]] = {}
63
+ order: list[str] = []
64
+ for child in children:
65
+ key = _local_name(child.tag, strip_namespaces)
66
+ if key not in groups:
67
+ groups[key] = []
68
+ order.append(key)
69
+ groups[key].append(_element_to_obj(child, attribute_prefix, text_key, strip_namespaces))
70
+ for key in order:
71
+ values = groups[key]
72
+ obj[key] = values[0] if len(values) == 1 else values
73
+
74
+ if text:
75
+ obj[text_key] = text
76
+
77
+ return obj
78
+
79
+
80
+ def execute_loadxml(
81
+ ctx: Any,
82
+ source_path: str | None = None,
83
+ attribute_prefix: str = _ATTR_PREFIX,
84
+ text_key: str = _TEXT_KEY,
85
+ strip_namespaces: bool = True,
86
+ ) -> dict:
87
+ """Lit un fichier XML et le convertit en JSON (conventions Newtonsoft).
88
+
89
+ Args:
90
+ source_path: chemin du fichier XML (absolu ou relatif au répertoire courant).
91
+ attribute_prefix: préfixe des propriétés issues d'attributs (défaut ``@``).
92
+ text_key: clé portant le texte d'un élément mixte (défaut ``#text``).
93
+ strip_namespaces: réduit ``{uri}local`` au nom local (défaut ``True``).
94
+
95
+ Returns:
96
+ Un objet ``{nom_racine: contenu}`` reflétant l'arbre XML.
97
+ """
98
+ if not source_path:
99
+ raise ValueError("loadxml: source_path est requis")
100
+
101
+ tree = _parse(source_path)
102
+ root = tree.getroot()
103
+ return {
104
+ _local_name(root.tag, strip_namespaces): _element_to_obj(
105
+ root, attribute_prefix, text_key, strip_namespaces
106
+ )
107
+ }
108
+
109
+
110
+ def register(registry: Any) -> None:
111
+ """Enregistre les fonctions du plugin dans un registre jslt (entry point)."""
112
+ registry.register(
113
+ "loadxml",
114
+ execute_loadxml,
115
+ description="Lit un fichier XML et le convertit en JSON (conventions Newtonsoft).",
116
+ )
File without changes
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-xml
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : lecture de fichiers XML (fonction de template loadxml).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,xml,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: Markup
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Requires-Dist: defusedxml>=0.7
27
+ Dynamic: license-file
28
+
29
+ # urban-json-xml
30
+
31
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : lecture de fichiers **XML**
32
+ dans les templates, via la fonction `loadxml`. Suit les conventions XML↔JSON du
33
+ `XmlNodeConverter` (.NET/Newtonsoft).
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install urban-json-xml # tire urban-json et defusedxml en dépendances
39
+ ```
40
+
41
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`) :
42
+ `loadxml` devient utilisable dans les templates.
43
+
44
+ ## Utilisation
45
+
46
+ ```python
47
+ from urban_json import JsltTemplate
48
+
49
+ # catalog.xml :
50
+ # <catalog>
51
+ # <book id="1"><title>A</title></book>
52
+ # <book id="2"><title>B</title></book>
53
+ # </catalog>
54
+ tpl = JsltTemplate.parse('[ { "$source": select(loadxml("catalog.xml"), $.catalog.book), "t": $.title } ]')
55
+ tpl.transform({})
56
+ # -> [{'t': 'A'}, {'t': 'B'}]
57
+ ```
58
+
59
+ `loadxml` renvoie un objet ; on navigue dedans avec `select`/`selectmany` (fonctions
60
+ du cœur) avant d'alimenter une boucle `$source`, un filtre `?(...)`, etc.
61
+
62
+ ## Conventions de conversion (Newtonsoft)
63
+
64
+ | XML | JSON |
65
+ |---|---|
66
+ | `<a>v</a>` | `{"a": "v"}` |
67
+ | `<a x="1">v</a>` | `{"a": {"@x": "1", "#text": "v"}}` |
68
+ | `<a/>` | `{"a": null}` |
69
+ | `<a><b>1</b><b>2</b></a>` | `{"a": {"b": ["1", "2"]}}` (frères homonymes → tableau) |
70
+
71
+ - Attributs → propriétés préfixées par `@`.
72
+ - Texte d'un élément mixte → clé `#text`.
73
+ - Les valeurs restent des **chaînes** (comme Newtonsoft, pas de coercition).
74
+
75
+ ## Signature
76
+
77
+ ```
78
+ loadxml(source_path, attribute_prefix="@", text_key="#text", strip_namespaces=true)
79
+ ```
80
+
81
+ | Paramètre | Rôle |
82
+ |---|---|
83
+ | `source_path` | chemin du fichier XML |
84
+ | `attribute_prefix` | préfixe des propriétés issues d'attributs (défaut `@`) |
85
+ | `text_key` | clé portant le texte d'un élément mixte (défaut `#text`) |
86
+ | `strip_namespaces` | réduit `{uri}local` au nom local (défaut `true`) |
87
+
88
+ ## Sécurité
89
+
90
+ Le XML est analysé avec [`defusedxml`](https://pypi.org/project/defusedxml/) :
91
+ entités externes et expansion d'entités désactivées (protection XXE /
92
+ « billion laughs »).
93
+
94
+ ## Licence
95
+
96
+ Apache-2.0.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/urban_json_xml/__init__.py
5
+ src/urban_json_xml/py.typed
6
+ src/urban_json_xml.egg-info/PKG-INFO
7
+ src/urban_json_xml.egg-info/SOURCES.txt
8
+ src/urban_json_xml.egg-info/dependency_links.txt
9
+ src/urban_json_xml.egg-info/entry_points.txt
10
+ src/urban_json_xml.egg-info/requires.txt
11
+ src/urban_json_xml.egg-info/top_level.txt
12
+ tests/test_loadxml.py
@@ -0,0 +1,2 @@
1
+ [urban_json.functions]
2
+ xml = urban_json_xml:register
@@ -0,0 +1,2 @@
1
+ urban-json
2
+ defusedxml>=0.7
@@ -0,0 +1 @@
1
+ urban_json_xml
@@ -0,0 +1,121 @@
1
+ """Tests du plugin urban-json-xml (fonction ``loadxml``).
2
+
3
+ Couvre : conventions de conversion (attributs ``@``, texte ``#text``, frères
4
+ homonymes → tableau, élément vide → null), namespaces, découverte via entry point,
5
+ usage en template, et sécurité (XXE / entités désactivées via defusedxml).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+ from defusedxml.common import EntitiesForbidden
14
+ from urban_json import FunctionRegistry, JsltTemplate
15
+
16
+ from urban_json_xml import execute_loadxml, register
17
+
18
+
19
+ def _write(tmp_path: Path, name: str, content: str) -> str:
20
+ path = tmp_path / name
21
+ path.write_text(content, encoding="utf-8")
22
+ return str(path)
23
+
24
+
25
+ def test_text_only_element(tmp_path: Path) -> None:
26
+ path = _write(tmp_path, "a.xml", "<a>v</a>")
27
+ assert execute_loadxml(None, path) == {"a": "v"}
28
+
29
+
30
+ def test_attributes_and_text(tmp_path: Path) -> None:
31
+ path = _write(tmp_path, "a.xml", '<a x="1">v</a>')
32
+ assert execute_loadxml(None, path) == {"a": {"@x": "1", "#text": "v"}}
33
+
34
+
35
+ def test_empty_element_is_null(tmp_path: Path) -> None:
36
+ path = _write(tmp_path, "a.xml", "<a/>")
37
+ assert execute_loadxml(None, path) == {"a": None}
38
+
39
+
40
+ def test_repeated_siblings_become_array(tmp_path: Path) -> None:
41
+ path = _write(tmp_path, "a.xml", "<a><b>1</b><b>2</b></a>")
42
+ assert execute_loadxml(None, path) == {"a": {"b": ["1", "2"]}}
43
+
44
+
45
+ def test_single_child_is_not_array(tmp_path: Path) -> None:
46
+ path = _write(tmp_path, "a.xml", "<a><b>1</b></a>")
47
+ assert execute_loadxml(None, path) == {"a": {"b": "1"}}
48
+
49
+
50
+ def test_nested_structure(tmp_path: Path) -> None:
51
+ xml = '<catalog><book id="1"><title>A</title></book><book id="2"><title>B</title></book></catalog>'
52
+ path = _write(tmp_path, "c.xml", xml)
53
+ assert execute_loadxml(None, path) == {
54
+ "catalog": {
55
+ "book": [
56
+ {"@id": "1", "title": "A"},
57
+ {"@id": "2", "title": "B"},
58
+ ]
59
+ }
60
+ }
61
+
62
+
63
+ def test_values_stay_strings(tmp_path: Path) -> None:
64
+ # Fidèle à Newtonsoft : pas de coercition de type (10 reste "10").
65
+ path = _write(tmp_path, "a.xml", "<a><n>10</n><b>true</b></a>")
66
+ assert execute_loadxml(None, path) == {"a": {"n": "10", "b": "true"}}
67
+
68
+
69
+ def test_strip_namespaces_default(tmp_path: Path) -> None:
70
+ xml = '<root xmlns:ns="http://ex"><ns:item>v</ns:item></root>'
71
+ path = _write(tmp_path, "ns.xml", xml)
72
+ assert execute_loadxml(None, path) == {"root": {"item": "v"}}
73
+
74
+
75
+ def test_keep_namespaces_when_disabled(tmp_path: Path) -> None:
76
+ xml = '<root xmlns:ns="http://ex"><ns:item>v</ns:item></root>'
77
+ path = _write(tmp_path, "ns.xml", xml)
78
+ result = execute_loadxml(None, path, strip_namespaces=False)
79
+ assert result == {"root": {"{http://ex}item": "v"}}
80
+
81
+
82
+ def test_custom_prefix_and_text_key(tmp_path: Path) -> None:
83
+ path = _write(tmp_path, "a.xml", '<a x="1">v</a>')
84
+ result = execute_loadxml(None, path, attribute_prefix="_", text_key="value")
85
+ assert result == {"a": {"_x": "1", "value": "v"}}
86
+
87
+
88
+ def test_register_into_custom_registry() -> None:
89
+ reg = FunctionRegistry()
90
+ register(reg)
91
+ assert "loadxml" in reg
92
+ assert reg.describe("loadxml").description
93
+
94
+
95
+ def test_discovered_via_entry_point() -> None:
96
+ from urban_json import default_registry, load_plugins
97
+
98
+ load_plugins(default_registry)
99
+ assert "loadxml" in default_registry
100
+
101
+
102
+ def test_loadxml_in_template(tmp_path: Path) -> None:
103
+ xml = "<catalog><book><title>A</title></book><book><title>B</title></book></catalog>"
104
+ path = _write(tmp_path, "c.xml", xml)
105
+ template = (
106
+ f'[ {{ "$source": select(loadxml("{path}"), $.catalog.book), "t": $.title }} ]'
107
+ )
108
+ assert JsltTemplate.parse(template).transform({}) == [{"t": "A"}, {"t": "B"}]
109
+
110
+
111
+ def test_xxe_external_entity_is_blocked(tmp_path: Path) -> None:
112
+ secret = _write(tmp_path, "secret.txt", "TOP SECRET")
113
+ xml = (
114
+ '<?xml version="1.0"?>'
115
+ f'<!DOCTYPE r [<!ENTITY xxe SYSTEM "file://{secret}">]>'
116
+ "<r>&xxe;</r>"
117
+ )
118
+ path = _write(tmp_path, "evil.xml", xml)
119
+ # defusedxml doit refuser l'entité (pas d'exfiltration du secret).
120
+ with pytest.raises(EntitiesForbidden):
121
+ execute_loadxml(None, path)