Cannot access elements with Linq-To-XML (C#)

S

Stefan Hoffmann

hi @all,

I must be blind at the moment. I'm trying to read elements from this
type of file:

<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.0"
creator="GPSBabel - http://www.gpsbabel.org"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0
http://www.topografix.com/GPX/1/0/gpx.xsd">
<time>2008-12-30T15:17:55Z</time>
<bounds minlat="48.154644012" minlon="10.806552887"
maxlat="48.341827393" maxlon="10.867885590"/>
<trk>
<name>track-1</name>
<desc>Log every 1 sec, 0 m</desc>
<trkseg>
<trkpt lat="48.341804504" lon="10.863015175">
<ele>539.265625</ele>
<time>2008-09-09T16:28:53Z</time>
<name>TP000001</name>
</trkpt>
</trkseg>
</trk>
</gpx>

Using this piece of code:

XDocument gpxDoc =
XDocument.Load(@"test.10.gpx");

Console.WriteLine(
String.Format("\nCreator: {0}\nVersion: {1}\n",
gpxDoc.Root.Attribute("creator").Value,
gpxDoc.Root.Attribute("version").Value));

var tracks = from trk in gpxDoc.Root.Elements("trk")
select trk;
int j = 0;
foreach (var track in tracks)
j++;
Console.WriteLine(j.ToString());

I can access the attributes, but not the <trk> elements. It returns 0.

Apparently I need a clue... Thanks.

(VisualStudio 2008, .Net 3.5)


mfG
--> stefan <--
 
M

Martin Honnen

Stefan said:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The root element and its descendants are in the namespace
http://www.topografix.com/GPX/1/0 so you need to use that namespace e.g.
XNamespace gpx = "http://www.topografix.com/GPX/1/0";
or
XNamespace gpx = gpxDoc.Root.Name.Namespace;
var tracks = from trk in gpxDoc.Root.Elements("trk")
select trk;

var tracks = gpxDoc.Root.Elements(gpx + "trk");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top