使用XmlDocument读取GPX文件

4
我正在尝试读取一个GPX文件(一种用于位置数据的XML文件)。它的结构如下:
<?xml version="1.0"?>
<gpx creator="GPX-service" version="1.1" 
xmlns="http://www.topografix.com/GPX/1/1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 
http://www.topografix.com/GPX/1/1/gpx.xsd">
<trk>
<name>Route</name>
<trkseg>
<trkpt lat="51.966738" lon="6.501578">
</trkpt>
<trkpt lat="51.966689" lon="6.501456">
</trkpt>
</trkseg>
</trk>
</gpx>

我过去曾经阅读过一百多个XML文件,但是这一个无法工作。我是按照以下方式读取GPX文件:

XmlDocument gpxDoc = new XmlDocument();
gpxDoc.Load(gpxfile);

XmlNodeList nl = gpxDoc.SelectNodes("trkpt");

foreach (XmlNode xnode in nl)
{
    string name = xnode.Name;

}

变量'gpxfile'是指向gpx文件的路径,这是正确的(已经测试过)。


什么出了问题? - Ofir Winegarten
1
我讨厌 System.xml!总是使用更简单、更全面的 System.Xml.Linq。如果你需要 Xml.Linq,我可以给你一个解决方案。 - Farzin Kanzi
1个回答

7

您需要使用命名空间。元素trkpt在当前上下文中不存在,只存在于命名空间http://www.topografix.com/GPX/1/1中。以下是如何使用这些命名空间的示例 - 让x成为该URI的别名。

XmlNamespaceManager nsmgr = new XmlNamespaceManager(gpxDoc.NameTable);
nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");            
XmlNodeList nl = gpxDoc.SelectNodes("//x:trkpt", nsmgr);

请注意,我们现在选择的节点是在x命名空间中的(例如//x:trkpt而不是//trkpt)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接