【问题标题】:WP7 XML insert into GPXWP7 XML 插入 GPX
【发布时间】:2012-09-15 19:35:43
【问题描述】:

在我的隔离存储中,我有一个名为 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);
}

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

【问题讨论】:

  • NullReferenceException in var rows = root.Descendants("trkpt");, DistribueretTeknologi12_GPSPhonePano.dll 中出现“System.NullReferenceException”类型的第一次机会异常
  • 我认为是因为它找不到 trkseg 但我不确定。

标签: c# xml windows-phone-7 gpx


【解决方案1】:

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

试试:

var root = doc1.Element("trk").Element("trkseg"); 

【讨论】:

  • 仍然在新行中捕获异常(NullReferenceException 未处理)。我也试过这个: var root = doc1.Element("gpx").Element("trk").Element("trkseg");因为我有一个名为 gpx 的元素的命名空间,但我仍然捕获异常。
  • 我尝试删除元素 GPX,然后使用您的代码,现在它可以工作了。但我需要 GPX 元素。
  • 当您尝试获取“gpx”元素时,您需要包含命名空间限定条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 2021-11-18
  • 2017-08-09
相关资源
最近更新 更多