我正在尝试阅读在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节点时,我会收到错误。
感谢任何帮助。
答案 0 :(得分:1)
尝试更改
XNamespace gpxtpx = XNamespace.Get("gpxtpx");
到
XNamespace gpxtpx = XNamespace.Get("http://www.garmin.com/xmlschemas/TrackPointExtension/v1");
答案 1 :(得分: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