Parsing an XML response to a query

£可爱£侵袭症+ 提交于 2019-12-11 00:08:20

问题


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.



来源:https://stackoverflow.com/questions/36164392/parsing-an-xml-response-to-a-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!