如何解析 KML 文件以从 Placemark 元素检索坐标点?

How can I parse a KML file to retrieve coordinate points from a Placemark element?

我有一个 KML 文件,其中包含 GPS 坐标以及每个坐标与下一个坐标的方位角。我想检索每个坐标和每个轴承并将它们存储在单独的列表中。一个包含严格的坐标,一个包含每个坐标。

为了问题的缘故,我将只列出我文件中的 2 个 Placemark 元素。 我的 KML 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Folder>
    <Placemark>
      <name>Coordinate0</name>
      <Point>
        <coordinates>44.601788291074442,-88.048173934221268</coordinates>
      </Point>
    </Placemark>

   <!-- more coordinates and bearings fill these gaps -->

   <Placemark>
      <name>Bearing200</name>
      <Point>
        <coordinates>284.25265584263923,0</coordinates>
      </Point>
    </Placemark>
  </Folder>
</kml>

我试过以下方法:

 //Function that parses through the file and pulls out coordinates and bearings for each coordinate

private void ButtonTestParser_Click(object sender, EventArgs e)
{
    //load the xml file
    XDocument xmlFile = XDocument.Load("Test.kml");
    //get every placemark element in the document
    var placemarks = (from x in xmlFile.Descendants()
                      where x.Name.LocalName == "Placemark"
                  select new XElement(x)).ToList();
    //loop through each placemark and separate it into coordinates and bearings
    List<string> coordinates = new List<string>();
    string coordinate = "";
    foreach(var point in placemarks)
    {
        coordinate = (from x in point.Descendants("coordinates")
                      select x).First().Value;
        coordinates.Add(coordinate);
    }
}

我收到以下错误:

System.InvalidOperationException: 'Sequence contains no elements'

你的问题就在这里

coordinate = (from x in point.Descendants("coordinates")
              select x).First().Value;

如果您查看 Descendants 的定义,您会发现它需要 XName,而不是 string

XName 只是命名空间和元素名称连接在一起。

所以一个简单的解决方法是将您的代码编写为:

var ns = xmlFile.Root.Name.Namespace;

coordinate = (from x in point.Descendants(ns + "coordinates")
              select x).First().Value;

请注意,您可以使用相同的技术来修复之前的代码:

var placemarks = (from x in xmlFile.Descendants(ns + "Placemark")

我冒昧地稍微重写了您的程序,因为您不需要所有 LINQ select...来自...代码:

//load the xml file
var document = XDocument.Load(@"C:\temp\bob.xml");
var ns = document.Root.Name.Namespace;
//get every placemark element in the document
var placemarks = document.Descendants(ns + "Placemark");

//loop through each placemark and separate it into coordinates and bearings
var coordinates = new List<string>();
var coordinate = "";
foreach (var point in placemarks)
{
    coordinate = point.Descendants(ns + "coordinates").First().Value;
    coordinates.Add(coordinate);
}