Reputation: 1427
I'm new to XML.Linq and can't work out how to create the XML output that I need. I'm almost there, but the data is appearing in the wrong tree structure:
static void Main(string[] args)
{
XElement GPX = new XElement("gpx",
new XAttribute("version", "1.0"),
new XAttribute("creator", "quilkin.com"),
new XElement("trk",
new XElement("name","to_do"),
new XElement("trkseg")
)
);
Track track = GarminTrack.ParseTCX("../../App_Data/25Oct_G2a.tcx");
int count = 0;
foreach (TrackPoint tp in track.TrackPoints)
{
Position pos = tp.Positionx[0];
GPX.Add(new XElement("trkpt",
new XAttribute("lat", pos.LatitudeDegrees),
new XAttribute("lon", pos.LongitudeDegrees),
new XElement("ele", tp.AltitudeMeters)));
count++;
}
Console.WriteLine(GPX);
Console.WriteLine(String.Format("{0} Track Points Processed.", count));
Console.ReadKey();
}
The output adds all the 'trkpt' elements to the root 'gpx', not to the 'trkseg' element.
<gpx version="1.0" creator="quilkin.com">
<trk>
<name>to_do</name>
<trkseg />
</trk>
<trkpt lat="50.262084" lon="-5.0499">
<ele>7</ele>
</trkpt>
<trkpt lat="50.262492" lon="-5.051214">
<ele>7</ele>
</trkpt>
<trkpt lat="50.261889" lon="-5.051892">
<ele>7</ele>
</trkpt>......
How do I get a handle to the 'trkseg' element so that I can add to it?
Upvotes: 0
Views: 41
Reputation: 2792
Here's how you could get the trackpoint into the trkseg element
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XMLAdd
{
class Program
{
static List<TrackPoint> trackpoints = new List<TrackPoint>
{
new TrackPoint
{
AltitudeMeters = 100,
Positionx = new Position[] { new Position { LatitudeDegrees = 200, LongitudeDegrees = 200} }
}
};
static void Main(string[] args)
{
// Save the trkseg element in a variable
var trkseg = new XElement("trkseg");
XElement GPX = new XElement("gpx",
new XAttribute("version", "1.0"),
new XAttribute("creator", "quilkin.com"),
new XElement("trk",
new XElement("name", "to_do"),
trkseg // <-- reference it here
)
);
int count = 0;
foreach (TrackPoint tp in trackpoints)
{
Position pos = tp.Positionx[0];
trkseg.Add(new XElement("trkpt", // <-- and here
new XAttribute("lat", pos.LatitudeDegrees),
new XAttribute("lon", pos.LongitudeDegrees),
new XElement("ele", tp.AltitudeMeters)));
count++;
}
Console.WriteLine(GPX);
Console.WriteLine(String.Format("{0} Track Points Processed.", count));
Console.ReadKey();
}
}
public class TrackPoint
{
public object AltitudeMeters { get; internal set; }
public Position[] Positionx { get; internal set; }
}
public class Position
{
public int LatitudeDegrees { get; internal set; }
public object LongitudeDegrees { get; internal set; }
}
}
Here the output for that:
<gpx version="1.0" creator="quilkin.com">
<trk>
<name>to_do</name>
<trkseg>
<trkpt lat="200" lon="200">
<ele>100</ele>
</trkpt>
</trkseg>
</trk>
</gpx>
1 Track Points Processed.
Upvotes: 1