Вопрос

I'm trying to read a GPX file created within a Garmin GPS device. I have the following code to try to pull out all the data, but it hangs up in the node and it's children, ie. =>

Here's the code

//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();

And the xml node

<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>

I can access all the other nodes just fine, but when trying to access the hr node, I get errors.

Any help is appreciated.

Это было полезно?

Решение

Try changing

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

to

XNamespace gpxtpx = XNamespace.Get("http://www.garmin.com/xmlschemas/TrackPointExtension/v1");

Другие советы

The name space suggestion above works, and I found it necessary to protect against null nodes:

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top