Parsing KML into the Feature Model
sapience ships with efficient parsers for the various XML formats, in this small tutorial I explain how you can use sapience to parse KML into the feature model, and how to access the annotations. The KML parser is not feature complete, e.g. all layouting parameters (the styles) are parsed but are not accessible through the feature model.
If you find bugs, misconceptions, or have any particular problems with the libraries, post them either on our message board or directly as a new Ticket here in Trac.
Dependencies
If you use maven, you are basically set, simply add the repository to your settings.xml, as described here, and add the following lines to your POM-file (replace VERSION with the current version number of sapience).
<dependency> <groupId>sapience</groupId> <artifactId>sapience-streams-kml</artifactId> <version>VERSION</version> </dependency>
If you don't want to use maven, you need the following libraries on your classpath
- sapience-streams-kml v0.1 ( Binary & Source)
- sapience-streams-main v0.1 ( Binary & Source)
- sapience-spatial-features v0.1 ( Binary & Source)
- sapience-annotations-model v0.1 ( Binary & Source)
- XStream v1.3.1 ( Binary & Source)
- Apache Commons IO v1.4 ( Binary & Source)
- Gavaghan's Geodesy (sapience-integration-geodesy) v1.1.1 ( Binary, Source)
- Java Topology Suite (JTS) v1.8 Binary & Source
Parsing KML
The following sample code expects an Input Stream (e.g. coming from File or a URL), and returns the according Feature Model. Here, we assume we have a KML file at hand.
String filename = "MyKMLFile.kml"; FileInputStream fis = new FileInputStream(filename); Streams parser = new KMLStream(); FeatureCollection features = parser.read(fis);
That's it. We use the XStreams library and StAX to parse KML, which means it is fairly efficient and works with large KML files as well.
In the next step, you could for example work with the coordinates.
Written by: pat