Skip to content

Commit

Permalink
add basic parse class method to KML #284
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Jul 26, 2024
1 parent 1dc645d commit 6d04f79
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 52 deletions.
45 changes: 0 additions & 45 deletions fastkml/kml.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,51 +157,6 @@ def append(
raise ValueError(msg)
self.features.append(kmlobj)

@classmethod
def class_from_string(
cls,
string: str,
*,
ns: Optional[str] = None,
name_spaces: Optional[Dict[str, str]] = None,
strict: bool = True,
) -> Self:
"""
Create a kml object from a string.
Args:
----
string: String representation (serialized XML) of the kml object
ns: Namespace of the element (default: None)
name_spaces: Dictionary of namespace prefixes and URIs (default: None)
strict: Whether to enforce strict parsing (default: True)
Returns:
-------
Geometry object
"""
try:
element = config.etree.fromstring(
string,
parser=config.etree.XMLParser(
huge_tree=True,
recover=True,
),
)
except TypeError:
element = config.etree.XML(string)
if ns is None:
ns = cast(str, element.tag[:-3] if element.tag.endswith("kml") else "")
name_spaces = name_spaces or {}
name_spaces = {**config.NAME_SPACES, **name_spaces}
return cls.class_from_element(
ns=ns,
name_spaces=name_spaces,
strict=strict,
element=element,
)

@classmethod
def parse(
cls,
Expand Down
16 changes: 9 additions & 7 deletions tests/kml_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Test the kml class."""
import io
import pathlib

import pygeoif as geo
Expand Down Expand Up @@ -133,13 +134,14 @@ class TestLxml(Lxml, TestStdLibrary):
"""Test with lxml."""

def test_from_string_with_unbound_prefix(self) -> None:
doc = """<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<ExtendedData>
<lc:attachment>image.png</lc:attachment>
</ExtendedData>
</Placemark> </kml>"""
k = kml.KML.class_from_string(doc)
doc = io.StringIO(
'<kml xmlns="http://www.opengis.net/kml/2.2">'
"<Placemark><ExtendedData>"
"<lc:attachment>image.png</lc:attachment>"
"</ExtendedData>"
"</Placemark> </kml>",
)
k = kml.KML.parse(doc, ns="{http://www.opengis.net/kml/2.2}")
assert len(k.features) == 1
assert isinstance(k.features[0], features.Placemark)

Expand Down

0 comments on commit 6d04f79

Please sign in to comment.