使用pandas读取komoot xml文件(gpx)

3
我想将由komoot生成的xml文件读入DataFrame中。以下是xml文件的结构:
<?xml version='1.0' encoding='UTF-8'?>
<gpx version="1.1" creator="https://www.komoot.de" 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">
  <metadata>
    <name>Title</name>
    <author>
      <link href="https://www.komoot.de">
        <text>komoot</text>
        <type>text/html</type>
      </link>
    </author>
  </metadata>
  <trk>
    <name>Title</name>
    <trkseg>
      <trkpt lat="60.126749" lon="4.250254">
        <ele>455.735013</ele>
        <time>2023-08-20T17:42:34.674Z</time>
      </trkpt>
      <trkpt lat="60.126580" lon="4.250247">
        <ele>455.735013</ele>
        <time>2023-08-20T17:42:36.695Z</time>
      </trkpt>
      <trkpt lat="60.126484" lon="4.250240">
        <ele>455.735013</ele>
        <time>2023-08-20T17:44:15.112Z</time>
      </trkpt>
    </trkseg>
  </trk>
</gpx>

我尝试了这段代码:

pd.read_xml('testfile.gpx',xpath='./gpx/trk/trkseg')

但不知怎么回事,我的xpath似乎有问题。具体来说,我遇到了这个ValueError错误。
ValueError: xpath does not return any nodes. Be sure row level nodes are in xpath. If document uses namespaces denoted with xmlns, be sure to define namespaces and use them in xpath.

我尝试了很多次,但是我选择的任何xpath都没有成功。

预期输出应该是什么样子? - undefined
@shaikmoeed 我想要一个包含每个trkpt的表格。我对pd.read_xml并不是很熟悉,所以即使在修复了xpath之后,可能还需要进行一些调整,但目标是拥有四列:纬度、经度、海拔和时间。 - undefined
1个回答

3
根据《ValueError》的指南,您需要在read_xml中传递一个namespace
df = (
    pd.read_xml(
        "testfile.gpx",
        xpath=".//doc:trkseg/doc:trkpt",
        namespaces={"doc": "http://www.topografix.com/GPX/1/1"}
    )
)

输出:

print(df)

         lat       lon         ele                      time
0  60.126749  4.250254  455.735013  2023-08-20T17:42:34.674Z
1  60.126580  4.250247  455.735013  2023-08-20T17:42:36.695Z
2  60.126484  4.250240  455.735013  2023-08-20T17:44:15.112Z

非常感谢。read_xml函数在运行之前会先下载http://www.topografix.com/GPX/1/1吗?所以这段代码只有在我连接到互联网时才能正常工作? - undefined
断开网络不会影响执行,你可以放心,它不会下载文档。 - undefined

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