我目前有一个来自Garmin Sat Nav的XML文件,我想用Java提取数据。但是,我找不到提取TRACK纬度和经度的方法,因为在单个节点内有多个具有相同名称的属性。我想过使用类似“getAttribute(”lat“)”的东西,但显然这只会返回第一个轨道段的第一个纬度: - (
我还没有开始这个项目,因为从XML文件中提取纬度和经度至关重要。
非常感谢任何帮助: - )
XML文件
<gpx xmlns="http://www.topografix.com/GPX/1/1"
xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" creator="Oregon
400t" version="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
http://www.garmin.com/xmlschemas/GpxExtensions/v3
http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd
http://www.garmin.com/xmlschemas/TrackPointExtension/v1
http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd">
<metadata>
<link href="http://www.garmin.com">
<text>Garmin International</text>
</link>
<time>2009-10-17T22:58:43Z</time>
</metadata>
<trk>
<name>Example GPX Document</name>
<trkseg>
<trkpt lat="47.644548" lon="-122.326897">
<ele>4.46</ele>
<time>2009-10-17T18:37:26Z</time>
</trkpt>
<trkpt lat="47.644548" lon="-122.326897">
<ele>4.94</ele>
<time>2009-10-17T18:37:31Z</time>
</trkpt>
<trkpt lat="47.644548" lon="-122.326897">
<ele>6.87</ele>
<time>2009-10-17T18:37:34Z</time>
</trkpt>
</trkseg>
嗨,我尝试了以下代码,但出于某种原因,我正在检索一个我甚至无法在我的XML文件中找到的值!
package Test;
import java.io.File;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.Document;
public class ReadXMLFile2 {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("J:/Desktop/Current.gpx"));
XPath xpath = XPathFactory.newInstance().newXPath();
System.out.println(xpath.evaluate("//trkseg/trkpt/@lat", document));
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您可能希望对/trkseg/trkpt/@lat
之类的属性进行XPath查询,以获得所有纬度。
答案 2 :(得分:0)
为了能够使用XPath,您首先需要使DocumentBuilderFactory
名称空间感知(由于历史原因,可能是因为历史原因而不是,因为XPath语言需要命名空间支持。)
现在,XML文件顶部的xmlns="http://www.topografix.com/GPX/1/1"
表示文档中所有未加前缀的元素名称都属于该命名空间。为了将它们与XPath匹配,您需要定义一个NamespaceContext
,将此命名空间URI绑定到前缀,并在XPath表达式中一致地使用该前缀。
或者,忘记XPath并使用标准DOM API可能更简单:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// enable namespace processing
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("J:/Desktop/Current.gpx"));
NodeList trkpts = document.getElementsByTagNameNS(
"http://www.topografix.com/GPX/1/1", "trkpt");
for(int i = 0; i < trkpts.getLength(); i++) {
Element pt = (Element)trkpts.item(i);
// since namespaces are enabled we must use the DOM level 2 getAttributeNS,
// not the legacy getAttribute, even though the attributes we're getting
// do not themselves belong to a namespace.
System.out.println("lat: " + pt.getAttributeNS(null, "lat") +
", long: " + pt.getAttributeNS(null, "lon"));
}