urban-json-xml 0.1.0__py3-none-any.whl

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,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,8 @@
1
+ urban_json_xml/__init__.py,sha256=s6cT5WESvLJNiTLlDZ02yQ3VsXKi4hX2Dr1hmQKU56g,4043
2
+ urban_json_xml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ urban_json_xml-0.1.0.dist-info/licenses/LICENSE,sha256=LdXMQzg0w6hrGI_vhgHsmOLKcHTkyF5PyUXkP9fV7mA,1068
4
+ urban_json_xml-0.1.0.dist-info/METADATA,sha256=0ANjqKNIfaYkpMK0M2vWti4StxRi3fpgD1jKWrpUy0k,3223
5
+ urban_json_xml-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ urban_json_xml-0.1.0.dist-info/entry_points.txt,sha256=d3TJ5yC7q8cRB1Tze6PUL3BDVcRqdAvuPR5q37OnDXE,53
7
+ urban_json_xml-0.1.0.dist-info/top_level.txt,sha256=tcM6fpfAE-AeUSuA8JgKu_AfR5q-jMt6wSGFi5zFe14,15
8
+ urban_json_xml-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [urban_json.functions]
2
+ xml = urban_json_xml:register
@@ -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 @@
1
+ urban_json_xml