首页 > 解决方案 > 使用 R 将 XML 转为数据框

问题描述

你好我有这样的xml数据,

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<gpx version="1.1" creator="Locus Map, Android"
 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"
 xmlns:gpx_style="http://www.topografix.com/GPX/gpx_style/0/2"
 xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3"
 xmlns:gpxtrkx="http://www.garmin.com/xmlschemas/TrackStatsExtension/v1"
 xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v2"
 xmlns:locus="http://www.locusmap.eu">
    <metadata>
        <desc>File with points/tracks from Locus Map/3.31.2</desc>
    </metadata>
<wpt lat="43.485033" lon="-74.949134">
    <ele>631.86</ele>
    <time>2018-06-25T18:14:39.850Z</time>
    <name>Fjdjxud</name>
    <pdop>2.10</pdop>
</wpt>
<wpt lat="43.485087" lon="-74.949118">
    <ele>627.29</ele>
    <time>2018-06-25T18:15:30.345Z</time>
    <name>2018-06-25 14:15:30</name>
    <pdop>2.10</pdop>
</wpt>
<wpt lat="43.485093" lon="-74.948893">
    <ele>629.72</ele>
    <time>2018-06-25T18:16:05.183Z</time>
    <name>2018-06-25 14:16:05</name>
    <pdop>2.10</pdop>
</wpt>
</gpx>

我需要将其转换为

A tibble: 6 x 2
    lon   lat
   <dbl> <dbl>
1 -74.9  43.5
2 -74.9  43.5
3 -74.9  43.5
4 -74.9  43.5
5 -74.9  43.5
6 -74.9  43.5

我试过了,

xmldataframe <- xmlToDataFrame("gpsdata.xml")
print(xmldataframe)

我搜索其他方法,但它无济于事,许多代码给我带来 0 行,我无法转换这个 xml 数据,谁能帮助我,非常感谢:)

标签: rxmlrstudio

解决方案


你可以试试 :

library(XML)
library(tibble)
data=htmlParse("C:/Users/.../yourxmlfile.xml")
lat=xpathSApply(data,"//@lat")
lon=xpathSApply(data,"//@lon")

lat=round(as.numeric(lat),1)
lon=round(as.numeric(lon),1)

df=as_tibble(data.frame(lon,lat))
# A tibble: 3 x 2
    lon   lat
  <dbl> <dbl>
1 -74.9  43.5
2 -74.9  43.5
3 -74.9  43.5

推荐阅读