Farooq
Farooq

Reputation: 91

Getting Data from XML REST Service and Display It Using R

I am trying to get Weather Data Using R from The RESTFUL WebService api.met.no.

The DATA is in ‌‌‌XML Format. I want to show Some Values from XML File.

When I fetch Data from the API and Try to display it .

<temperature id="TTT" unit="celsius" value="2.8"/> 

I am fairly New to these Technologies.

I want to know Is there anyway to display it Like Tempreture=2.8

Here is my Code

    rootnode <- xmlRoot(result)
rootsize <- xmlSize(rootnode)
print(rootsize)
rootnode <- xmlRoot(result)
print(rootnode[[2]][[1]])
print(rootnode[[2]][[1]][[1]][[1]])

Upvotes: 1

Views: 1061

Answers (2)

hrbrmstr
hrbrmstr

Reputation: 78792

Or you could just use the R package that was designed to do this:

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 ...

Upvotes: 1

agustin
agustin

Reputation: 1351

You are nearly there. You can split all attributes from a given node using the xmlToList function from the XML Package. Here the code to get the temperature from the given 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"])

xmlToListreturns a vector which can be easily accessed using the name or index value

Upvotes: 0

Related Questions