我想將 XML 轉換為資料框。我知道 XML::xmlToDataFrame,但它在我的情況下給出了錯誤。XML 可在此處找到:https : //api.data.gov.hk/v1/historical-archive/get-file?url=https://resource.data.one.gov.hk/td/traffic -detectors/rawSpeedVol-all.xml&time=20211216-0513
感謝所有的答案!
uj5u.com熱心網友回復:
由于您的 XML 檔案包含多個嵌套子項,XML::xmlToDataFrame因此出現錯誤。
我已經使用天真的方法解決了這個問題,但它有效!這是我所做的:
下面的代碼創建了一個dataframe在 `' 中帶有標簽的 。
library(xml2)
require(XML)
pg <- read_xml("https://s3-ap-southeast-1.amazonaws.com/historical-resource-archive/2021/12/16/https%3A%2F%2Fresource.data.one.gov.hk%2Ftd%2Ftraffic-detectors%2FrawSpeedVol-all.xml/0513")
records <- xml_find_all(pg, "//lane")
nodenames<-xml_name(xml_children(records))
nodevalues<-trimws(xml_text(xml_children(records)))
lane_id <- nodevalues[seq(1, length(nodevalues), 6)]
speed <- nodevalues[seq(2, length(nodevalues), 6)]
occupancy <- nodevalues[seq(3, length(nodevalues), 6)]
volume <- nodevalues[seq(4, length(nodevalues), 6)]
s.d. <- nodevalues[seq(5, length(nodevalues), 6)]
valid <- nodevalues[seq(6, length(nodevalues), 6)]
df <- data.frame(lane_id, speed, occupancy, volume, s.d., valid)
head(df)
該df如下所示:
lane_id speed occupancy volume s.d. valid
1 Fast Lane 70 0 0 0 Y
2 Middle Lane 76 6 3 11.1 Y
3 Slow Lane 70 6 0 0 Y
4 Fast Lane 82 1 1 0 Y
5 Middle Lane 63 3 1 0 Y
6 Slow Lane 79 2 1 0 Y
如果要提取 的資料<detectors>,可以使用以下代碼:
################ Extract Detector Data #########
records2 <- xml_find_all(pg, "//detector")
vals2 <- trimws(xml_text(records2))
nodenames2 <-xml_name(xml_children(records2))
nodevalues2 <-trimws(xml_text(xml_children(records2)))
detector_id <- nodevalues2[seq(1, length(nodevalues2), 3)]
direction <- nodevalues2[seq(2, length(nodevalues2), 3)]
lanes <- nodevalues2[seq(3, length(nodevalues2), 3)]
df2 <- data.frame(detector_id, direction, lanes)
head(df2)
該df2如下所示:
detector_id direction lanes
1 AID01101 South East Fast Lane70000YMiddle Lane766311.1YSlow Lane70600Y
2 AID01102 North East Fast Lane82110YMiddle Lane63310YSlow Lane79210Y
3 AID01103 South East Fast Lane50000YMiddle Lane65210YSlow Lane192310Y
4 AID01104 North East Fast Lane50000YSlow Lane63110Y
5 AID01105 North East Fast Lane50100YSlow Lane53410Y
6 AID01106 South East Fast Lane50300YSlow Lane56510Y
但是,正如您所注意到的,該lanes列并未按照您的意愿進行清理,因為它是 XML 中的孫標記。
雖然,你可以創建一個新的資料幀df,并df2為你想。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/385829.html
下一篇:使用XML填充表格
