1

在我的隔离存储中,我有一个名为 Route.gpx 的文件,它是使用以下代码创建的:

using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("Route.gpx", FileMode.Create, myStore))
{
    XNamespace ns = "http://www.topografix.com/GPX/1/1";
    XNamespace xsiNs = "http://www.w3.org/2001/XMLSchema-instance";
    XDocument xDoc = new XDocument(
        new XDeclaration("1.0", "UTF-8", "no"),
        new XElement(ns + "gpx",
            new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
            new XAttribute(xsiNs + "schemaLocation",
                "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"),
            new XAttribute("creator", "XML tester"),
            new XAttribute("version", "1.1"),
            new XElement(ns + "trk",
                new XElement(ns + "trkseg",
                    new XElement(ns + "trkpt",
                        new XAttribute("lat", "7.0"),
                        new XAttribute("lon", "19.0"),
                        new XElement(ns + "time", DateTime.Now.ToString("yyyy-MM-ddThh:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture))
                        )))));
    xDoc.Save(myStream);

但是现在我想添加一个额外的trkpt元素,我尝试过使用以下代码:

XDocument doc1;
using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("Route.gpx", FileMode.Open, myStore))
{
    doc1 = XDocument.Load(myStream);
}

var root = doc1.Element("trkseg");
var rows = root.Descendants("trkpt");
var lastRow = rows.Last();
lastRow.AddAfterSelf(
//XElement trkseg =
      new XElement("trkpt",
          new XElement("time", DateTime.Now.ToString("yyyy-MM-ddThh:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture))));

using (IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("Route.gpx", FileMode.Create, myStore))
{
    doc1.Save(myStream);
}

我从这里得到 的代码只是捕获一个异常然后按下。

4

1 回答 1

0

您正在尝试将“trkseg”元素作为根对象的后代访问,而您在较低级别创建它。

尝试:

var root = doc1.Element("trk").Element("trkseg"); 
于 2012-09-24T22:13:01.463 回答