Skip to content

Commit 9b65916

Browse files
committed
refactor: get_xml_type is better
1 parent 1058ee0 commit 9b65916

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

json2xml/dicttoxml.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import numbers
66
from collections.abc import Callable, Sequence
77
from random import SystemRandom
8-
from typing import Any, Dict, Union
8+
from typing import Any, Dict, Union, TypeAlias
99

1010
from defusedxml.minidom import parseString
1111

@@ -14,6 +14,13 @@
1414
# Set up logging
1515
LOG = logging.getLogger("dicttoxml")
1616

17+
XML_TYPES = {"str", "unicode", "int", "long", "float", "bool", "number", "null"}
18+
XMLValue: TypeAlias = Union[
19+
str, int, float, bool, numbers.Number,
20+
Sequence[str], datetime.datetime, datetime.date,
21+
None, dict[str, Any]
22+
]
23+
1724
_RANDOM = SystemRandom()
1825

1926
def make_id(element: str, start: int = 100000, end: int = 999999) -> str:
@@ -77,24 +84,18 @@ def get_xml_type(val: ELEMENT) -> str:
7784
Returns:
7885
str: The XML type.
7986
"""
80-
if val is not None:
81-
if type(val).__name__ in ("str", "unicode"):
82-
return "str"
83-
if type(val).__name__ in ("int", "long"):
84-
return "int"
85-
if type(val).__name__ == "float":
86-
return "float"
87-
if type(val).__name__ == "bool":
88-
return "bool"
89-
if isinstance(val, numbers.Number):
90-
return "number"
91-
if isinstance(val, dict):
92-
return "dict"
93-
if isinstance(val, Sequence):
94-
return "list"
95-
else:
87+
if val is None:
9688
return "null"
97-
return type(val).__name__
89+
type_name = type(val).__name__
90+
if type_name in XML_TYPES:
91+
return type_name
92+
if isinstance(val, numbers.Number):
93+
return "number"
94+
if isinstance(val, dict):
95+
return "dict"
96+
if isinstance(val, Sequence):
97+
return "list"
98+
return type_name
9899

99100

100101
def escape_xml(s: str | numbers.Number) -> str:

0 commit comments

Comments
 (0)