我正在尝试使用RESTFUL WebService api.met.no中的R获取天气数据。
DATA是XML格式。我想从XML文件中显示一些值。
当我从API获取数据并尝试显示它时。
<temperature id="TTT" unit="celsius" value="2.8"/>
我对这些技术很新。
我想知道无论如何都要显示它像Tempreture = 2.8
这是我的代码
rootnode <- xmlRoot(result)
rootsize <- xmlSize(rootnode)
print(rootsize)
rootnode <- xmlRoot(result)
print(rootnode[[2]][[1]])
print(rootnode[[2]][[1]][[1]][[1]])
答案 0 :(得分:1)
或者您可以使用专为此目的而设计的R包:
library(weatherr)
forecast <- locationforecast(lat=60.10, lon=9.58)
str(forecast)
## 'data.frame': 89 obs. of 14 variables:
## $ time : POSIXct, format: "2016-03-22 00:00:00" "2016-03-22 01:00:00" ...
## $ temperature : num 0.6 0.6 0.6 0.7 1.3 2 3.1 3.9 4.5 5.1 ...
## $ windDirection : num 342.1 277 269.8 308.3 31.1 ...
## $ windSpeed_mps : num 0.7 0.3 0.4 0.7 0.6 0.5 0.6 1.4 1.6 1.2 ...
## $ windSpeed_beaufort : num 1 0 0 1 1 0 1 1 1 1 ...
## $ windSpeed_name : Factor w/ 4 levels "Flau vind","Lett bris",..: 1 3 3 1 1 3 1 1 1 1 ...
## $ windGust : num 0.7 0.3 0.4 0.7 0.7 1.2 1.7 2.7 3 2.5 ...
## $ humidity : num 79.3 86.7 88.8 81 80.5 75.7 70.8 70.8 70.1 66.2 ...
## $ pressure : num 1006 1006 1006 1006 1006 ...
## $ cloudiness : num 76.6 72.8 68.9 66.4 59.5 40.7 77.7 81.1 96 96.8 ...
## $ lowClouds : num 18.7 34.4 39.9 22.5 6 0.3 0.5 3.7 17.1 41.2 ...
## $ mediumClouds : num 32.6 30.1 18.2 3.2 0.8 0.1 0 0 0 0.1 ...
## $ highClouds : num 62.1 48.7 42.5 55.4 56.8 40.4 77.6 80.8 95.8 94.5 ...
## $ dewpointTemperature: num -2.7 -1.5 -1.3 -2.4 -1.8 -2 -1.9 -1.1 -0.7 -0.9 ...
答案 1 :(得分:0)
你快到了。您可以使用xmlToList
中的XML Package
函数拆分给定节点的所有属性。这里是从给定API获取温度的代码:
# Install and load required packages
install.packages("XML")
require("XML")
# Save the URL of the xml file in a variable
metUrl <- "http://api.met.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58"
# Parse xml file directly from the API
xmlMetResponse <- xmlParse(metUrl)
# Access the top node
xmlMetTop <- xmlRoot(xmlMetResponse)
# Make a list of the desired subnode
metResponseDesiredNode <- xmlToList(xmlMetTop[[2]][[1]][[1]][[1]])
# Get temperature ("value") from desired subnode
metTemperature <- as.numeric(metResponseDesiredNode["value"])
xmlToList
返回一个可以使用名称或索引值