Search code examples
c#.netkmlwktnettopologysuite

how can you convert KML to WKT in c#?


I can easily convert WKT to KML using the nettopologysuite, with something like:

WKTReader wktR = new WKTReader();
GeoAPI.Geometries.IGeometry geom = wktR.Read(wktString);
KMLWriter writer = new KMLWriter();
string kml = writer.Write(geom);

but i can't find any documentation or ideas on how to go the other way around. I would think i would need a KMLReader object from nettopologysuite IO KML, but there is only a writer. Is there a way to do this that I'm not seeing?


Solution

  • You are correct - NetTopologySuite does not have any functionality to read KML. This is likely because KML is oriented heavily towards map overlay functionality, and has a number of structures (like Photo and Screen overlays) that don't translate into more generic geometry structures.

    KML does have equivalent general geometry primitives though (points, lines, polygons), so you'll just need some way to load them and then you can implement transforms.

    The most direct path is to identify which KML elements you need, and implement a two step transform. Load them with a library such as SharpKml.Core (flattening and extract structures of interest), then implement builders to convert them to NTS equivalents. Documentation on how to extract elements of interest from the KML is accessible here: https://github.com/samcragg/sharpkml/blob/master/docs/ExtractingElements.md