[英]Adding elements to a XML child
我是 XML.Linq 的新手,不知道如何創建我需要的 XML 輸出。 我快到了,但數據出現在錯誤的樹結構中:
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();
}
輸出將所有“trkpt”元素添加到根“gpx”,而不是“trkseg”元素。
<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>......
我如何獲得“trkseg”元素的句柄以便我可以添加到它?
以下是將跟蹤點放入 trkseg 元素的方法
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; }
}
}
這里的輸出:
<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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.