2013-03-06 192 views
5

我試圖自動從this government website的API下載一些數據。如何向API發送XML請求R

網站指示:

All requests for this version should be made to the following URL: 
http://api.finder.healthcare.gov/v2.0/ 

我可以找到大量的有關如何發送XML請求的信息,但沒有一個例子是R特異性..並有大量的R代碼裏面,在那裏,展示瞭如何使用XML,httrRCurl包,但我找不到在SO或r-help郵件列表中找到任何示例的實際發送 xml請求。 ..有更多文檔解析響應。

the government website上,如果您單擊PlansForIndividualOrFamily Samples示例,它將顯示需要發送的xml請求(代碼如下)。

url <- "http://api.finder.healthcare.gov/v2.0/" 

xml.request <- 
    "<?xml version='1.0' encoding='UTF-8'?> 
    <PrivateOptionsAPIRequest> 
     <PlansForIndividualOrFamilyRequest> 
      <Enrollees> 
       <Primary> 
        <DateOfBirth>1990-01-01</DateOfBirth> 
        <Gender>Male</Gender> 
        <TobaccoUser>Smoker</TobaccoUser> 
       </Primary> 
      </Enrollees> 
      <Location> 
       <ZipCode>69201</ZipCode> 
       <County> 
        <CountyName>CHERRY</CountyName> 
        <StateCode>NE</StateCode> 
       </County> 
      </Location> 
      <InsuranceEffectiveDate>2012-10-01</InsuranceEffectiveDate> 
     <IsFilterAnalysisRequiredIndicator>false</IsFilterAnalysisRequiredIndicator> 
     <PaginationInformation> 
      <PageNumber>1</PageNumber> 
      <PageSize>10</PageSize> 
     </PaginationInformation> 
     <SortOrder> 
      <SortField>OOP LIMIT - INDIVIDUAL - IN NETWORK</SortField> 
      <SortDirection>ASC</SortDirection> 
     </SortOrder> 
     <Filter/> 
     </PlansForIndividualOrFamilyRequest> 
    </PrivateOptionsAPIRequest>" 
+0

你碰巧知道如何發送XML請求到http://api.finder.healthcare.gov/v2.0/? – obautista 2013-11-22 04:22:31

回答

9

使用RCurl你這樣做;

myheader=c(Connection="close", 
      'Content-Type' = "application/xml", 
      'Content-length' =nchar(xml.request)) 
data = getURL(url = url, 
        postfields=xml.request, 
        httpheader=myheader, 
        verbose=TRUE) 

就是這樣。然後您可以使用XML包的xpathApply來檢索數據。例如要獲得家庭ID:

library(XML) 
xmltext <- xmlTreeParse(data, asText = TRUE,useInternalNodes=T) 
unlist(xpathApply(xmltext,'//Plan/PlanID',xmlValue)) ## change the right xpath here 

"29678NE0780012" "29678NE0780011" "29678NE0140010" 
    "29678NE0780010" "29678NE0140019" "29678NE0140018" "29678NE0140017" 
    "29678NE0140016" "29678NE0780005" "29678NE0780004" 
+1

壯麗。謝謝 :) – 2013-03-06 07:56:51