Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading in XML/KML files using C#

I'm trying to import the kml xml Google earth file into an application, but i can't seem to get the xDocument syntax right in order to do what i want, i'm wondering if anyone could suggest a way to read in the kml xml file.

I understand the basics of xml import but can't get anything working with xDocument and Linq, ideally i'd like to get each Placemark as an object and add them to my Entity Framework driven db. Any suggestions as to how i should do this would be great, as i'm just starting out with Linq and could do with some pointers. The xml is laid out as below

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
  <Document>
    <Placemark>
      <name>XXX</name>
      <description>XXX</description>
      <styleUrl>XXX</styleUrl>
      <Point>
         <coordinates>XXX</coordinates>
      </Point>
    </Placemark>
    <Placemark>
      <name>XXX</name>
      <description>XXX</description>
      <styleUrl>XXX</styleUrl>
      <Point>
         <coordinates>XXX</coordinates>
      </Point>
    </Placemark>
  </Document>
</kml>
like image 705
norbert Avatar asked Oct 08 '12 19:10

norbert


2 Answers

You didn't include any code, but I would guess that you forgot to include your namespace when referencing things. Here is an example.

Basic access:

var placemarks = xdoc.Element("kml").Element("Document").Elements("Placemark");

Using namespaces:

var ns = XNamespace.Get("http://earth.google.com/kml/2.2");
var placemarks = xdoc.Element(ns + "kml").Element(ns + "Document").Elements(ns + "Placemark");
like image 147
Guvante Avatar answered Oct 22 '22 22:10

Guvante


My guess is that you've forgotten to use the namespace in your LINQ to XML queries. It's easy enough to extract the data from this:

XNamespace ns = "http://earth.google.com/kml/2.2";
var doc = XDocument.Load("file.xml");
var query = doc.Root
               .Element(ns + "Document")
               .Elements(ns + "Placemark")
               .Select(x => new PlaceMark // I assume you've already got this
                       {
                           Name = x.Element(ns + "name").Value,
                           Description = x.Element(ns + "description").Value,
                           // etc
                       });

If that doesn't help, please post a complete example of what you've tried, and what went wrong.

like image 7
Jon Skeet Avatar answered Oct 22 '22 21:10

Jon Skeet