通过此post,我知道我可以.find()
,.findall()
和.text()
来获取嵌套在代码中的值。
以下面的.gpx文件为例,
<?xml version="1.0"?>
<gpx version="1.1" creator="Trails 1.28 - https://www.trails.io" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www8.garmin.com/xmlschemas/TrackPointExtensionv2.xsd" xmlns:trailsio="http://trails.io/GPX/1/0" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://trails.io/GPX/1/0 https://trails.io/GPX/1/0/trails_1.0.xsd">
<metadata>
<time>2016-03-27T06:30:06Z</time>
</metadata>
<trk>
<name><![CDATA[xyz]]></name>
<extensions><trailsio:TrackExtension><trailsio:activity>trekking</trailsio:activity></trailsio:TrackExtension></extensions>
<trkseg>
<trkpt lat="22.491121" lon="114.137634">
<ele>41.270</ele>
<time>2016-03-27T01:21:21Z</time>
</trkpt>
<trkpt lat="22.491104" lon="114.137612">
<ele>42.777</ele>
<time>2016-03-27T01:21:38Z</time>
</trkpt>
</trkseg>
</trk>
</gpx>
如果我想获得高程,我可以尝试:
gpx = etree.parse("D:/Users/perry/Downloads/abc.gpx")
ele = gpx.findall("{http://www.topografix.com/GPX/1/1}trk")
ele = [x.findall("{http://www.topografix.com/GPX/1/1}trkseg") for x in ele][0]
ele = [x.findall("{http://www.topografix.com/GPX/1/1}trkpt") for x in ele][0]
ele = [x.findall("{http://www.topografix.com/GPX/1/1}ele") for x in ele]
[x[0].text for x in ele]
输出为['41.270', '42.777']
,这就是我想要的!太好了!
但是,我想使用.xpath()
,但
gpx.xpath("//ele")
,
gpx.xpath("//{http://www.topografix.com/GPX/1/1}ele")
和
gpx.xpath("//ele", namespaces = {'ele': "http://www.topografix.com/GPX/1/1"})
返回[]
或错误“lxml.etree.XPathEvalError:表达式无效”。
如何使用.xpath()
获取高程?
谢谢!
答案 0 :(得分:1)
你走在正确的轨道上:
gpx.xpath("//ele", namespaces = {'ele': "http://www.topografix.com/GPX/1/1"})
由于XML中存在默认命名空间,因此其上的XPath //ele
无法在ele
命名空间中找到http://www.topografix.com/GPX/1/1
元素。< / p>
因此,必须在XPath提供程序中注册前缀,您已完成此操作。但是,您需要使用它的已注册前缀来引用该元素。所以以下内容将起作用:
gpx.xpath("//gpx:ele", namespaces = {'gpx': "http://www.topografix.com/GPX/1/1"})