Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read GPX file with XmlDocument

I'm trying to read a GPX-file (a kind of XML file for location data). This is the structure:

<?xml version="1.0"?>
<gpx creator="GPX-service" version="1.1" 
xmlns="http://www.topografix.com/GPX/1/1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 
http://www.topografix.com/GPX/1/1/gpx.xsd">
<trk>
<name>Route</name>
<trkseg>
<trkpt lat="51.966738" lon="6.501578">
</trkpt>
<trkpt lat="51.966689" lon="6.501456">
</trkpt>
</trkseg>
</trk>
</gpx>

I'v readed in more than hundred XML-files in the past, but this one will not work. I'm reading the GPX-file in this way:

XmlDocument gpxDoc = new XmlDocument();
gpxDoc.Load(gpxfile);

XmlNodeList nl = gpxDoc.SelectNodes("trkpt");

foreach (XmlNode xnode in nl)
{
    string name = xnode.Name;

}

Variable 'gpxfile' is the path to the gpxfile, which is correct (tested).

like image 659
Sven Nijs Avatar asked Sep 12 '25 17:09

Sven Nijs


1 Answers

You need to work with namespaces. The element trkpt does not exist in the current context, only in the namespace http://www.topografix.com/GPX/1/1. Here's an example how you work with said namespaces - let x be an alias to the URI.

XmlNamespaceManager nsmgr = new XmlNamespaceManager(gpxDoc.NameTable);
nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");            
XmlNodeList nl = gpxDoc.SelectNodes("//x:trkpt", nsmgr);

Note that we select nodes in the x namespace now (e.g. //x:trkpt instead of //trkpt).

like image 94
Wolfgang Radl Avatar answered Sep 15 '25 09:09

Wolfgang Radl