From 852402584450024019d75c1640eff477688144ea Mon Sep 17 00:00:00 2001 From: apurvabanka Date: Thu, 7 Nov 2024 00:38:33 -0500 Subject: [PATCH] KML Write Function --- fastkml/kml.py | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/fastkml/kml.py b/fastkml/kml.py index 7c5dab89..e5d62ea5 100644 --- a/fastkml/kml.py +++ b/fastkml/kml.py @@ -27,6 +27,7 @@ """ import logging from pathlib import Path +import pathlib from typing import IO from typing import Any from typing import AnyStr @@ -122,7 +123,7 @@ def etree_element( """ # self.ns may be empty, which leads to unprefixed kml elements. # However, in this case the xlmns should still be mentioned on the kml - # element, just without prefix. + # element, just without prefix.""" if not self.ns: root = config.etree.Element( f"{self.ns}{self.get_tag_name()}", @@ -164,26 +165,6 @@ def parse( name_spaces: Optional[Dict[str, str]] = None, strict: bool = True, ) -> Self: - """ - Parse a KML file and return a KML object. - - Args: - ---- - file: The file to parse. - Can be a file path (str or Path), or a file-like object. - - Keyword Args: - ------------ - ns (Optional[str]): The namespace of the KML file. - If not provided, it will be inferred from the root element. - name_spaces (Optional[Dict[str, str]]): Additional namespaces. - strict (bool): Whether to enforce strict parsing rules. Defaults to True. - - Returns: - ------- - KML object: The parsed KML object. - - """ try: tree = config.etree.parse( file, @@ -208,6 +189,27 @@ def parse( element=root, ) + def write( + self, + file_name:pathlib.Path, + *, + prettyprint:bool=False, + xml_declaration:bool=False + ) -> None: + + element = self.etree_element() + + tree = config.etree.tostring( + element, + encoding="UTF-8", + pretty_print=prettyprint, + ).decode( + "UTF-8", + ) + + with open(file_name, "wb") as file: + tree.write(file, encoding="UTF-8", xml_declaration=xml_declaration) + registry.register( KML,