我将GPS数据存储为.tcx文件。 这是一个xml文件(请求下面的文件)
<?xml version="1.0" encoding="utf-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tp1="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpx="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Other">
<Id>2012-01-17T11:44:35Z</Id>
<Lap StartTime="2012-01-17T11:44:35Z">
<TotalTimeSeconds>0</TotalTimeSeconds>
<DistanceMeters>0</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2012-01-17T11:44:35Z</Time>
<Position>
<LatitudeDegrees>59.720211518183351</LatitudeDegrees>
我使用的唯一类似的东西是使用类似格式的apple .plists,虽然信息嵌套在我认为的<dictionary>
标签中。
以下内容会给我嵌套的词典......
import plistlib
pl = plistlib.readPlist('/Users/name/Documents/file.plist')
for sub_dict in pl:
print(sub_dict['keyA'])
print(sub_dict['keyD'])
print(sub_dict['keyE'])
print(sub_dict['keyG'])
我知道xml.dom.minidom,etree和lxml,但是我无法解决如何获得与上面的plistlib模块相同的输出。
我的最终目标是能够将两个数据集中的选定键合并在一起。一步一步......
编辑-----------------
我有一些工作:
from xml.dom.minidom import parse
doc = parse('/Users/name/Documents/GPS/gps.tcx')
lat = doc.getElementsByTagName("LatitudeDegrees")
time = doc.getElementsByTagName("Time")
for x in lat:
print(x.firstChild.data)
答案 0 :(得分:1)
我必须在发布的XML中添加结束标记,以便lxml解析器可以解析它。
完成后,可以使用doc.xpath
调用拉出Time和LatitudeDegrees数据。
import lxml.etree as ET
import io
content='''<?xml version="1.0" encoding="utf-8"?>
<TrainingCenterDatabase xmlns="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tp1="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpx="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2 http://www.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd">
<Activities>
<Activity Sport="Other">
<Id>2012-01-17T11:44:35Z</Id>
<Lap StartTime="2012-01-17T11:44:35Z">
<TotalTimeSeconds>0</TotalTimeSeconds>
<DistanceMeters>0</DistanceMeters>
<Calories>0</Calories>
<Intensity>Active</Intensity>
<TriggerMethod>Manual</TriggerMethod>
<Track>
<Trackpoint>
<Time>2012-01-17T11:44:35Z</Time>
<Position>
<LatitudeDegrees>59.920211518183351</LatitudeDegrees>
</Position>
</Trackpoint>
</Track>
</Lap>
</Activity>
</Activities>
</TrainingCenterDatabase>
'''
doc = ET.fromstring(content)
ns = {'ns':'http://www.garmin.com/xmlschemas/TrainingCenterDatabase/v2'}
for trackpoint in doc.xpath('//ns:Trackpoint', namespaces = ns):
print(trackpoint.xpath('(ns:Time|ns:Position/ns:LatitudeDegrees)/text()', namespaces = ns))
产量
['2012-01-17T11:44:35Z', '59.920211518183351']