Parsing an XML response to a query

2019-07-09 04:36发布

问题:

I am trying to extract the County fips number for a large number of lines of longitude and latitude. I can get the data from an FCC API, but am having a hard time reading it into R.

For example, when I run the following code in R:

library(httr)
fips <- GET("http://data.fcc.gov/api/block/find", query = list(latitude = 48.9905, longitude = -122.2733, showall="false"))

result <- content(fips, as = "parsed")

result

the object "result" is displayed as follows

{xml_document}
<Response>
[1] <Block FIPS="530730102002091"/>
[2] <County FIPS="53073" name="Whatcom"/>
[3] <State FIPS="53" code="WA" name="Washington"/>

The information I am interested in is the county FIPS code "53073." How should I go about extracting just that number?

回答1:

You have to parse the XML returned from that API

library("httr")
library("XML")
fips <- GET("http://data.fcc.gov/api/block/find", query = list(latitude = 48.9905, longitude = -122.2733, showall="false"))
result <- content(fips, as = "parsed")
> xmlToList(xmlParse(result))$County["FIPS"]
   FIPS 
"53073" 


回答2:

Another option is to use the code in the following link: Latitude/Longitude to FIPS Codes via the FCC's API.

# FCC's Census Block Conversions API
# http://www.fcc.gov/developers/census-block-conversions-api

install.packages("RCurl")
install.packages("RJSONIO")

latlong2fips <- function(latitude, longitude) {
  url <- "http://data.fcc.gov/api/block/find?format=json&latitude=%f&longitude=%f"
  url <- sprintf(url, latitude, longitude)
  json <- RCurl::getURL(url)
  json <- RJSONIO::fromJSON(json)
  as.character(json$County['FIPS'])
}

# Orange County
latlong2fips(latitude=28.35975, longitude=-81.421988)

I believe there is a query limit, but I haven't quite determined what that is yet.



标签: xml r api census