This project has moved. For the latest updates, please go here.
A common requirement for processing Kml files is to extract a particular element from the file and then do some processing with them. For example, we might want to extract the Polygons from the following Kml:
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns=''>
      <name>hollow box</name>
      <Polygon id='TestPolygon'>
To do that we can use the Flatten extension method, which enables us to iterate all the elements and can then filter them out using LINQ, like so:
using System;
using System.IO;
using System.Linq;
using System.Text;
using SharpKml.Dom;
using SharpKml.Engine;

class Program
   const string Xml =
@"<?xml version='1.0' encoding='UTF-8'?>
... as above ...

    static void Main(string[] args)
        // First get the Kml into a KmlFile object
        KmlFile file;
        using (var stream = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(Xml)))
            file = KmlFile.Load(stream);

        // Use the Flatten extension method to iterate over all the elements
        // then use the Linq extension OfType to select only Polygons
        foreach (var poly in file.Root.Flatten().OfType<Polygon>())


Last edited Jun 1, 2011 at 9:09 PM by samcragg, version 1


No comments yet.