Reading in XML/KML files using C#

c# entity-framework kml linq xml

Question

I'm attempting to import a kml xml Google Earth file into a program, but I can't seem to get the xDocument syntax to work properly. If anybody has any suggestions, that would be great.

I am familiar with the fundamentals of xml import, but I am unable to make anything with xDocument and Linq work. Ideally, I would want to get each Placemark as an object and add them to my Entity Framework-driven database. I'm new to Linq and could use some tips, so any advice on how I should go about doing this would be much appreciated. The xml is organized as follows.

<?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>
1
10
4/5/2018 11:47:47 AM

Accepted Answer

Although you didn't supply any code, I'd assume that you did not remember to include your namespace when referring items. Here's an illustration.

Simple access

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

Namespace use

var ns = XNamespace.Get("http://earth.google.com/kml/2.2");
var placemarks = xdoc.Element(ns + "kml").Element(ns + "Document").Elements(ns + "Placemark");
8
10/8/2012 7:34:09 PM

Popular Answer

My guess is that in your LINQ to XML queries, you've neglected to utilize the namespace. The data may be easily extracted 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 it is unsuccessful, please provide a detailed description of what you attempted and what went wrong.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow