1

我正在尝试读取在 Garmin GPS 设备中创建的 GPX 文件。我有以下代码尝试提取所有数据,但它挂在节点中并且它是子节点,即。=>

这是代码

//returns http://www.topografix.com/GPX/1/1
XNamespace gpx = GetGpxNameSpace();
XDocument gpxDoc = GetGpxDoc();
XNamespace gpxtpx = XNamespace.Get("gpxtpx");
var waypoints = from waypoint in gpxDoc.Descendants(gpx + "trkpt")
                select new
                {
                    Latitude = waypoint.Attribute("lat").Value,
                    Longitude = waypoint.Attribute("lon").Value,
                    Elevation = waypoint.Element(gpx + "ele") != null ?
                        waypoint.Element(gpx + "ele").Value : null,
                    Dt = waypoint.Element(gpx + "time") != null ?
                        waypoint.Element(gpx + "time").Value : null,
                    hr = waypoint.Element(gpx+ "extensions").Element(gpxtpx +"TrackPointExtension").Element(gpxtpx +"hr").Value
                };

StringBuilder sb = new StringBuilder();
foreach (var wpt in waypoints)
{
    // This is where we'd instantiate data
    // containers for the information retrieved.
    sb.Append(
        string.Format("Name:{0} Latitude:{1} Longitude:{2} Elevation:{3} Date:{4}\n",
        "x", wpt.Latitude, wpt.Longitude,
        wpt.Elevation, wpt.Dt));
}

return sb.ToString();

和 xml 节点

<trkseg>
   <trkpt lon="-111.5252978168428" lat="35.07395471446216">
      <ele>2084.800048828125</ele>
      <time>2012-07-15T14:47:16.000Z</time>
      <extensions>
         <gpxtpx:TrackPointExtension>
            <gpxtpx:hr>155</gpxtpx:hr>
         </gpxtpx:TrackPointExtension>
      </extensions>
   </trkpt>
...
</trkseg>

我可以很好地访问所有其他节点,但是在尝试访问 hr 节点时,出现错误。

任何帮助表示赞赏。

4

2 回答 2

1

尝试改变

XNamespace gpxtpx = XNamespace.Get("gpxtpx");

XNamespace gpxtpx = XNamespace.Get("http://www.garmin.com/xmlschemas/TrackPointExtension/v1");
于 2013-06-13T18:00:12.597 回答
0

上面的命名空间建议有效,我发现有必要防止空节点:

HeartRate = trackpoint.Element(gpx + "extensions") != null ?
                                      (trackpoint.Element(gpx + "extensions").Element(gpxtpx + "TrackPointExtension") != null ?
                                       (trackpoint.Element(gpx + "extensions").Element(gpxtpx + "TrackPointExtension").Element(gpxtpx +"hr") != null ? 
                                          trackpoint.Element(gpx + "extensions").Element(gpxtpx + "TrackPointExtension").Element(gpxtpx +"hr").Value : null ) : null   ) : null
于 2013-07-31T12:31:58.590 回答