Skip to content

Commit

Permalink
Refactor XML subelement handling in KML class
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Dec 20, 2023
1 parent 77921b8 commit 768a44c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 15 deletions.
2 changes: 1 addition & 1 deletion fastkml/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def xml_subelement(


def xml_subelement_list(
obj: _BaseObject,
obj: _XMLObject,
*,
element: Element,
attr_name: str,
Expand Down
36 changes: 22 additions & 14 deletions fastkml/kml.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
from fastkml.containers import Folder
from fastkml.enums import Verbosity
from fastkml.features import Placemark
from fastkml.helpers import xml_subelement_list
from fastkml.helpers import xml_subelement_list_kwarg
from fastkml.overlays import GroundOverlay
from fastkml.overlays import PhotoOverlay
from fastkml.types import Element
Expand Down Expand Up @@ -84,19 +86,23 @@ def etree_element(
try:
root = config.etree.Element( # type: ignore[attr-defined]
f"{self.ns}kml",
# nsmap={None: self.ns[1:-1]},
)
except TypeError:
root = config.etree.Element( # type: ignore[attr-defined]
f"{self.ns}kml",
)
for feature in self.features:
root.append(feature.etree_element(precision=precision, verbosity=verbosity))
xml_subelement_list(
obj=self,
element=root,
attr_name="features",
precision=precision,
verbosity=verbosity,
)
return cast(Element, root)

def append(self, kmlobj: Union[Folder, Document, Placemark]) -> None:
"""Append a feature."""
if id(kmlobj) == id(self):
if kmlobj is self:
msg = "Cannot append self"
raise ValueError(msg)
self.features.append(kmlobj)
Expand All @@ -116,18 +122,20 @@ def _get_kwargs(
element=element,
strict=strict,
)
name_spaces = kwargs["name_spaces"]
assert name_spaces is not None
kwargs["features"] = []
for klass in (Document, Folder, Placemark, GroundOverlay, PhotoOverlay):
for feature in element.findall(f"{ns}{klass.__name__}"):
kwargs["features"].append(
klass.class_from_element( # type: ignore[attr-defined]
ns=ns,
name_spaces=name_spaces,
element=feature,
strict=strict,
),
)

kwargs["features"].extend(
xml_subelement_list_kwarg(
element=element,
ns=ns,
name_spaces=name_spaces,
kwarg="features",
obj_class=klass,
strict=strict,
).get("features", []),
)
return kwargs

@classmethod
Expand Down

0 comments on commit 768a44c

Please sign in to comment.