簡體   English   中英

將xml解析為R數據幀時出現問題?

[英]Problems in parsing xml to R data frame?

我是R新手,並且絕對是xml格式的新手,所以如果對此問題有明確的答案,請原諒我。

我正在嘗試從xml文件創建具有特定對象的數據框,並且有兩個問題。

  1. 當我將URL中的xml文件內容讀入R(我使用htmlTreeParse)時,它似乎是一個長字符串,而不是我在xml文件中看到的通常格式。 我嘗試使用其他URL,但沒有出現此問題。 這與xml內容中間的“ ?? @@@”系列有關嗎? (URL: http : //opentrip.atlantaregion.com/otp-rest-servlet/ws/plan?&fromPlace=33.87725673930016%2C-84.46014404296875&toPlace=33.74946419232578%2C-84.38873291015625&time=1%3A13pm&date=03-21-2014&mode=TRANSIT %2CWALK&maxWalkDistance = 750&arriveBy = false&showIntermediateStops = false&itinIndex = 0 )。

  2. 我對如何將xml內容分配給數據框,獲取其中的某些部分以及分配給不同的變量有些迷惑。

到目前為止,我已經附加了我的R代碼,以防萬一。

謝謝,我很感謝大家的見解! 再次,我很抱歉,如果答案很明顯。

我的R代碼:

xml.url <- "http://opentrip.atlantaregion.com/otp-rest-servlet/ws/plan?&fromPlace=33.87725673930016%2C-84.46014404296875&toPlace=33.74946419232578%2C-84.38873291015625&time=1%3A13pm&date=03-21-2014&mode=TRANSIT%2CWALK&maxWalkDistance=750&arriveBy=false&showIntermediateStops=false&itinIndex=0"

xmlfile <- htmlTreeParse(xml.url)

該網站會根據其詢問的對象來量身定制其內容。 您需要詢問它向您發送xml內容。 另外,您可能需要為其提供用戶代理。 這可以通過RCurl完成

library(XML)
library(RCurl)
xml.url <- "http://opentrip.atlantaregion.com/otp-rest-servlet/ws/plan?&fromPlace=33.87725673930016%2C-84.46014404296875&toPlace=33.74946419232578%2C-84.38873291015625&time=1%3A13pm&date=03-21-2014&mode=TRANSIT%2CWALK&maxWalkDistance=750&arriveBy=false&showIntermediateStops=false&itinIndex=0"
myAgent <- "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0"
myAccept <- "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
library(XML)
library(RCurl)
xData <- getURL(xml.url, useragent = myAgent, encoding = "UTF-8"
                ,httpheader = c(Accept = myAccept))
xmlfile <- htmlParse(xData) #, encoding = "UTF8")

或者,如果您不要求它提供XML ,它將返回您JSON ,您可以使用RJSONIO或類似的方法進行解析:

library(RJSONIO)
jData <- fromJSON(xml.url)
> names(jData)
[1] "requestParameters" "plan"              "error"             "debug"            
> jData$requestParameters
date                                   mode 
"03-21-2014"                         "TRANSIT,WALK" 
arriveBy                  showIntermediateStops 
"false"                                "false" 
fromPlace                              itinIndex 
"33.87725673930016,-84.46014404296875"                                    "0" 
toPlace                                   time 
"33.74946419232578,-84.38873291015625"                               "1:13pm" 
maxWalkDistance 
"750" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM